How do i get the value of a datalist item with a button click

user3746002 picture user3746002 · Jun 16, 2014 · Viewed 8.5k times · Source

I have a dataList with a command button, i want to click the button and obtain the value of a field in the datalist view of the button i have clicked.

I have tried various solutions but keep getting

{"Object reference not set to an instance of an object."}

here is my datalist

<asp:DataList ID="DataList1" runat="server" DataKeyField="ID" DataSourceID="SqlDataSource1" Width="579px" OnItemCommand = "Datalist1_ItemCommand">
    <ItemTemplate>
        Epic:
        <asp:Label ID="EpicLabel" runat="server" Text='<%# Eval("Epic") %>' />
        <br />
        ID:
        <asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' />
        <br />
        Company:
        <asp:Label ID="CompanyLabel" runat="server" Text='<%# Eval("Company") %>' />
        <br />
        Date:
        <asp:Label ID="DateLabel" runat="server" Text='<%# Eval("Date") %>' />
        <br />
        time:
        <asp:Label ID="timeLabel" runat="server" Text='<%# Eval("time") %>' />
        <br />
        NewsItem:
        <asp:Label ID="NewsItemLabel" runat="server" Text='<%# Eval("NewsItem") %>' />
        <br />
        HeadLine:
        <asp:Label ID="HeadLineLabel" runat="server" Text='<%# Eval("HeadLine") %>' />
        <br />

        <asp:Button ID="Button1" runat="server" CommandArgument='<%# Eval("Epic", "{0}") %>' Text="Button" />

<br />
    </ItemTemplate>
</asp:DataList>

and her is my code behind

    public void Datalist1_ItemCommand(object sender, DataListCommandEventArgs e)

    {
        var button = sender as Button;

       /// if (button == null) return;

        var dataListItem = button.NamingContainer as DataListItem;

        if (dataListItem == null) return;

        var currentKey = DataList1.DataKeys[dataListItem.ItemIndex];

        var myLabel = button.Parent.Controls.Cast<Control>().FirstOrDefault(x => x.ID == "Epic") as Label;

      ///  if (myLabel == null) return;

        var myLabelText = myLabel.Text;
    }

Answer

Ali picture Ali · Jun 17, 2014

You code do this using the following changes on your code;

on your button control:

 <asp:Button ID="Button1" runat="server" CommandName="myCommand" Text="Button" />

on your ItemCommand event:

    protected void DataList1_ItemCommand(object source, 
                                        DataListCommandEventArgs e)
    {
        switch (e.CommandName)
        { 
            case "myCommand":
                // more code could go here

                Label myLabel = (Label)e.Item.FindControl("EpicLabel");
                var myLabelText = myLabel.Text;

                // more code could go here
                break;
        }
    }