Click here to Skip to main content
15,919,931 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm having trouble with FindControl in DataList
My aspx:
ASP.NET
<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:
C#
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;
        
    }
Posted
Updated 30-May-12 20:19pm
v2

1 solution

use this code


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



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

<pre></pre>

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900