I have a custom control that has a search function. When the user clicks search, the code generates a list of buttons based on the results of the search.
Each button's CommandArgument property contains the Id of the search result. When the user clicks the button, I want to handle the event, get the CommandArgument and raise an event back to the main page with the value.
The problem is that the buttons aren't raising the event. I would assume this is because it gets lost on a postback or whatever. Should I consider an alternative way of listing the values to make this work?
Whats the simplest way of getting around this? Here's what I have:
private void Search()
{
foreach (var c in companies)
{
TableRow companyRow = new TableRow();
TableCell nameRowCell = new TableCell();
TableCell regRowCell = new TableCell();
Button selectButton = new Button();
selectButton.CommandArgument = c.Id.ToString();
selectButton.Text = c.Name;
selectButton.Click += new EventHandler(selectButton_Click);
selectButton.CausesValidation = false;
nameRowCell.Controls.Add(selectButton);
companyRow.Cells.Add(nameRowCell);
tblCompanies.Rows.Add(companyRow);
}
}
void selectButton_Click(object sender, EventArgs e) // <- Not getting handled
{
Button btn = (Button)sender;
string id = btn.CommandArgument;
if (id != "" && CompanyFound != null)
CompanyFound(new Company() { Id = int.Parse(id) });
}
I've been playing with your code and it does put a button on the screen. The browser source shows the button in the form of an input type submit tag. To test that it is in fact firing add a div to your page somewhere, maybe set it's id to testDiv. Then in your selectButton_Click event hander add a line to the effect of: testDiv.innerHtml = "made it here".
If the div changes, your button fired.
Also, maybe add protected, public or something before the void on the selectButton_Click.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.