从嵌套的datalist中检索控制值

时间:2018-04-18 11:38:13

标签: c# asp.net

我正在尝试从嵌套的asp.net datalist控件中检索标签控件的值,但是收到错误:"对象引用未设置为Response.Write中的对象实例(id。文本);线"

hmtl代码

<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>

背后的代码

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);
    }
}

代码有什么问题?

1 个答案:

答案 0 :(得分:0)

你必须为嵌套的datalist(dlChild)创建OnItemDataBound事件

<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>   

背后的代码

  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);
                }
            }
        }