0

I am trying to retrieve a label control's value from a nested asp.net datalist control but getting an error: "Object reference not set to an instance of an object at Response.Write(id.Text); line"

hmtl code

<asp:DataList ID="dlParent" runat="server" DataKeyField="RequestId" OnItemDataBound="DataList1_ItemDataBound">
    <ItemTemplate>
        <asp:Label ID="Label1" runat="server" Text='<%# Bind("RequestId") %>'></asp:Label>
        <asp:DataList ID="dlChild" runat="server">
            <ItemTemplate>
                <asp:Label ID="lblid" runat="server" Text='<%# Bind("workshopid") %>'></asp:Label></ItemTemplate>
        </asp:DataList>
    </ItemTemplate>
</asp:DataList>

code behind

protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        string key = dlParent.DataKeys[e.Item.ItemIndex].ToString();

        DataList dlChild = (DataList)e.Item.FindControl("dlParent");

        Label id = (Label)dlParent.FindControl("lblid");
        Response.Write(id.Text);
    }
}

What's wrong with the code?

Abdul Gafoor M
  • 107
  • 1
  • 3
  • 9
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – VDWWD Apr 18 '18 at 11:51
  • Remember that you need to access both DataList Controls index-based if you want to find items inside the ItemTemplate. – VDWWD Apr 18 '18 at 11:54

1 Answers1

0

you must creaete OnItemDataBound event for nested datalist (dlChild)

<asp:DataList ID="dlParent" runat="server" DataKeyField="RequestId" OnItemDataBound="DataList1_ItemDataBound">


     <ItemTemplate>
            <asp:Label ID="Label1" runat="server" Text='<%# Bind("RequestId") %>'></asp:Label>
            <asp:DataList ID="dlChild" runat="server" OnItemDataBound="dlChild_ItemDataBound">
                <ItemTemplate>
                    <asp:Label ID="lblid" runat="server" Text='<%# Bind("workshopid") %>'></asp:Label></ItemTemplate>
            </asp:DataList>
        </ItemTemplate>
    </asp:DataList>   

code behind

  protected void dlChild_ItemDataBound(object sender, DataListItemEventArgs e)
        {

         if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var lblid = e.Item.FindControl("lblid") as Label;
                if (lblid != null)
                {
                    Response.Write(lblid .Text);
                }
            }
        }
Morteza Jangjoo
  • 1,780
  • 2
  • 13
  • 25