I have a datalist control which some controls(ex: button) are in it. I want to write some code into click event of button which is in the datalist control. But in the code behind page I can't see the name of controls into datalist. How can I solve this problem?
+2
A:
Attach your event to the controls in the OnItemCreated event of the datalist.
EDITED TO ADD SAMPLE
private void DataList_ItemCreated(object sender,
System.Web.UI.WebControls.DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Button btn = (Button)e.Item.FindControl("btnWhatever");
if (btn != null) btn.Click += new EventHandler(SomHandler);
}
}
cmsjr
2009-01-09 14:44:32
Can you make it simpler? some sample code can help.
mavera
2009-01-09 14:51:40
Sure, thing. Check out the edit and let me know if that's clear.
cmsjr
2009-01-09 14:54:04
Thanks! It's clear enough ;)
mavera
2009-01-09 15:11:02
A:
I tried to make it with this way, but there are many controls which are in datalist, so I think there should a simple way about it. Arn't anyway else to make it?
mavera
2009-01-10 10:27:05
+1
A:
If you don't want to add a handler to all the child events, you could instead add your code to the OnItemCommand.
<asp:DataList id="DataList1" runat="server">
<ItemTemplate>
<asp:Button ID="btnDoSomething" Runat=server CommandName="DoSomething"
CommandArgument="<%# DataBinder.Eval(Container.DataItem, "SomeID")
%>"></asp:LinkButton>
</ItemTemplate>
</asp:DataList>
protected void DataList1_ItemCommand(
object source, DataListCommandEventArgs e)
{
if (e.CommandName == "DoSomething")
{
//Do stuff
}
}
cmsjr
2009-01-10 11:24:05