views:

431

answers:

3

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
Can you make it simpler? some sample code can help.
mavera
Sure, thing. Check out the edit and let me know if that's clear.
cmsjr
Thanks! It's clear enough ;)
mavera
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
+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
That's what I want is. Thanks
mavera