DataList中的问题FindControl [英] Problem FindControl in DataList

查看:55
本文介绍了DataList中的问题FindControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用DataList中的FindControl
我的aspx:

I''m having trouble with FindControl in DataList
My aspx:

<form id="form1" runat="server">
    <div>
    
        <asp:DataList ID="DataList1" runat="server">
        <ItemTemplate>
        <asp:Label runat="server" ID="lbl" Text='<%#Eval("idProduct") %>'></asp:Label>
        <asp:Button runat="server" ID="btn" Text='select' onclick="btn_Click"/>
        </ItemTemplate>
        </asp:DataList>
    
    </div>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>


代码:


code:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind();
        }
        if (Session["idProduct"] != null)
        {
            Label1.Text = Session["idProduct"].ToString();
        }
    }

    void Bind()
    {
        Product Prd = new Product();
        DataTable dt = n.Get();
        DataList1.DataSource = dt;
        DataList1.DataBind();
    }
    protected void btn_Click(object sender, EventArgs e)
    {
        Label l = (Label)DataList1.FindControl("lbl");
        //when click btn,I get:Object reference not set to an instance of an object.
        Session["idProduct"] = l.Text;
        
    }

推荐答案

使用此代码


use this code


<form id="form1" runat="server">
    <div>

        <asp:DataList ID="DataList1" runat="server">
        <ItemTemplate>
        <asp:Label runat="server" ID="lbl" Text='<%#Eval("idProduct") %>'></asp:Label>
        <pre><asp:Button runat="server" ID="btn" Text='select' commandname="Pro" commandargument='<%#Eval("idProduct") %>' onclick="btn_Click"/>


</ItemTemplate>
</asp:DataList>

</div>
< asp:Label ID ="Label1" runat ="server" Text ="Label"></asp:Label>
</form>




</ItemTemplate>
</asp:DataList>

</div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>



protected void datalist_itemcommand(object sender, EventArgs e)
{
if(e.commandname=="Pro")
{
string product=e.commandargument.tostring();
Session["idProduct"] = product;
}
}

<pre></pre>



这篇关于DataList中的问题FindControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆