2012-02-01 126 views
0

我寫在asp.net的web應用程序, 在後面的代碼,我有這樣的代碼:使事件的多個按鈕,並知道被點擊了哪個按鈕

foreach(UserDetails _UD in m_TeachersDetailsList)  
{ 
    Button button = new Button();// a Button control 
    button.Text = "click"; 
    button.ID = "SelectedTeacher"; 
    TableCell tableCell = new TableCell();// a Cell control 
    tableCell.Controls.Add(button); 
    TableRow tableRow = new TableRow(); 
    tableRow.Cells.Add(tableCell); // a table row 
    TableSearchResult.Rows.Add(tableRow); // a table that had been created in the aspx 
} 

我怎樣才能讓一個事件,當你點擊按鈕時,你將會看到一個功能, 以及如何知道哪個按鈕被點擊並帶我進入我的功能。 謝謝。

+0

先試一下。 – 2012-02-01 17:04:58

+2

你試圖用相同的ID創建多個控件,我不認爲它會工作,你試過嗎? – 2012-02-01 17:06:10

+0

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.click.aspx應該讓你去... – Chris 2012-02-01 17:06:11

回答

1

你這樣做

int id = 0; 
foreach(UserDetails _UD in m_TeachersDetailsList)  
{ 
    Button button = new Button();// a Button control 
    button.Text = "click"; 
    button.ID = "selectedTeacher" + id++; 
    TableCell tableCell = new TableCell();// a Cell control 
    tableCell.Controls.Add(button); 
    TableRow tableRow = new TableRow(); 
    tableRow.Cells.Add(tableCell); // a table row 
    TableSearchResult.Rows.Add(tableRow); // a table that had been created in the aspx 
    button.Click += new EventHandler(this.button_Click); 
} 

,共同的事件處理程序

protected void button_Click(object sender, EventArgs e) 
{ 
    //This way you will get the button clicked 
    Button button = (Button)sender; 

} 

重要

您將需要添加OnInit控件。

希望這對你有用。

+3

-1沒有評論,讓我知道的原因 - 1 – 2012-02-01 17:21:51

+0

最重要的是「重要」:)。必須放在init中!我花了大約2小時試圖弄清楚爲什麼地獄不工作! Thx – Makis 2015-08-12 13:36:51

0

ASPX

asp:Button ID="btnTest" runat="server" onclick="btn_Click" 

代碼隱藏

protected void btn_Click(object sender, EventArgs e) 
{ 
    Button mybutton = (Button)sender; 
    Response.Write(mybutton.ID); 
} 

只需使用btn_Click作爲的onclick爲每個按鈕。然後使用「發件人」來確定哪個控件發送了請求。

1

不要設置按鈕的id,讓它默認。設置按鈕的CommandArgument屬性,而不是:

foreach (UserDetails _UD in m_TeachersDetailsList)  
{ 
    Button button = new Button();// a Button control 
    button.Text = "click"; 
    button.CommandArgument = _UD.UserDetailID.ToString(); // some unique identifier 

    // this is optional, if you need multiple actions for each UserDetail: 
    button.CommandName = "SomeAction"; // optional 

    button.Command += new EventHandler(detailButton_Handler); 

    // ...etc... 
} 

那麼你的處理器需要檢查CommandNameCommandArgument值:

public void detailButton_Handler(object sender, EventArgs e) 
{ 
    string DetailID = e.CommandArgument.ToString(); 
    switch (e.CommandName.ToString()) 
    { 
     case "SomeAction": 
     /// Now you know which Detail they clicked on 
      break; 

     case "OtherAction": 
      break; 
    } 
} 
+0

+1,'CommandArgument'是一個更好的解決方案(同樣,祝賀10K = P) – jadarnel27 2012-02-01 17:54:24

+1

@ jadamel27:謝謝!遊戲化ftw! – egrunin 2012-02-01 17:58:03