Dynamic control and its Event
We are creating dynamic text boxes and buttons inside a grid for each row. Now we want to create click event for each button. To create button inside the grid 开发者_StackOverflow社区in using ITemplate.
Code:
ImageButton imbtnAdd = new ImageButton();
imbtnAdd.ID = "imbtn" + columnName;
imbtnAdd.ImageUrl = "btn_add_icon.gif";
imbtnAdd.Width = 20;
container.Controls.Add(imbtnAdd);
Error:
I have used imbtnAdd.Click += new ImageClickEventHandler(imbtnAdd_Click);
but it shows an error message
imbtnAdd_Click does not exist
ImageButton imbtnAdd = new ImageButton();
imbtnAdd.ID = "imbtn" + columnName;
imbtnAdd.ImageUrl = "btn_add_icon.gif";
imbtnAdd.Width = 20;
imbtnAdd.Click += imbtnAdd_Click;
container.Controls.Add(imbtnAdd);
// ...
private void imbtnAdd_Click(object sender, EventArgs e)
{
// handle event
}
Jrista's answer is correct.
Although, if you want to implement different handlers for all the buttons and you are using .Net 3.0 or above, you can use lambdas:
imbtnAdd.Click += (object sender, EventArgs e) =>
{
// Code handling code goes here...
};
精彩评论