Question

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?

Was it helpful?

Solution

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

  }

}

OTHER TIPS

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);
        }
    } 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top