Similar to this question here ASP.Net Dynamic Command Button Event Not Firing but with a slightly different problem.
Provided below is a (very) condensed version of my code.
protected void Page_Load(object sender, EventArgs e)
{
RenderDataItems();
}
private void RenderDataItems()
{
pnlDataItems.Controls.Clear()
DataTable dt = MyClass.GetAllData();
foreach (DataRow dr in dt.Rows)
{
Button b = new Button();
b.Command += new CommandEventHandler(SelectItem);
b.CommandArgument = dr["ID"].ToString();
b.ID = "btnData" + dr["ID"].ToString();
if (hdnDataListID.Value == dr["ID"].ToString())
{
b.Text = "Selected Item";
}
else
{
b.Text = "Pick This Item";
}
pnlDataItems.Controls.Add(b);
}
}
private void SelectItem(object sender, CommandEventArgs e)
{
hdnDataListID.Value = e.CommandArgument.ToString();
RenderDataItems();
}
private void EditSelectItem(int id)
{
MyClass mc = new MyClass(id);
hdnDataListID.Value = mc.ID.ToString();
RenderDataItems();
}
The method SelectItem
is only called by the button controls rendered within the RenderDataItems
method. The EditSelectItem
is called by a separate control that is created dynamically, but does not require the altering that the buttons in the RenderDataItems
method requires.
I've run the debugger and stepped through the code to see what happens. When the page is loaded, the RenderDataItems
is called from the PageLoad
and populates the panel with all of the buttons having "Pick This Text" (because the HiddenField control's value (hdnDataListID
) has not been set).
The first time I click one of the buttons, the RenderDataItems
from PageLoad
fires, followed by the initial population of the buttons, the HiddenField's value is set to the ID, and the second RenderDataItems
call happens from within the SelectItem
method. The buttons are cleared, and recreated. The correct button has the "Selected Item" text.
The second time I click one of the buttons, the RenderDataItems
from PageLoad
fires, followed by the initial population of the buttons, but the SelectItem
method never fires.
The third time I click one of the buttons, the same functionality happens as the 1st time. The 4th mimics the 2nd. The 5th mimics the 1st. And so on, and so on.
When using the EditSelectItem
method from the controls not contained within the panel (it's a DataSource bound GridView row with buttons that calls this method), it does exactly as I'd expect and properly sets the selected / unselected buttons, with calls to both the RenderDataItems
and the EditSelectItem
method every time.
Any ideas?
P.S. I've already removed all of my AJAX on this page.