Click here to Skip to main content
15,906,569 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have datalist which has items

and under every item there is a link

VB
<asp:LinkButton runat="server" ID="Add" OnClick="lnkAdd_Click"
                Text="Add to cart" CommandName="Add" />


I make event handler for this link like that

C#
protected void lnkAdd_Click(object sender, EventArgs e)
  {
    //  int ProId =Convert.ToInt32(((Label)ListView_Products.Controls[0].FindControl("IDLabel")).Text);

      int ProductID = int.Parse("ItemID");
      AddToShoppingCart(ProductID);
      Response.Redirect("ShoppingCartaspx.aspx");
  }

my question
how to get productID from datalist ???
it gives me error null reference

thanks in advance .
Posted

Try:
Following binds the ItemID to the CommandArgument of the LinkButton.
XML
<asp:LinkButton ID="LinkButton1" runat="server" Text="Add to cart"
   OnClick="LinkButton1_Click" CommandArgument='<%# Eval("ItemID") %>' />


You can then retrieve it like this in the code behind:
C#
protected void LinkButton1_Click(object sender, EventArgs e)
{
  LinkButton myButton = sender as LinkButton;
  if (myButton != null)
  {
     int id = Convert.ToInt32(myButton.CommandArgument);
  }
}

The sender holds a reference to the LinkButton that triggered the event handler.
You can cast the object into a LinkButton and then retrieve its CommandArgument and cast that into an int.
 
Share this answer
 
Comments
Sarah Mohammed77 29-Apr-12 9:28am    
thank you so much it works for me
Rambo_Raja 21-Nov-13 0:28am    
+5
Sandeep Mewara 29-Apr-12 9:57am    
:thumbsup:
Use This Syntax
C#
DataListItem dl = ((DataListItem)(DataControlFieldCell(((ImageButton)sender).Parent).Parent));

Int32 var = Convert.Toint32(((Label)dl.FindControl("lbl")).ToString());
 
Share this answer
 
v2
If you have many products and want to make multi-selection enable, then just use below code inside for loop.
C#
Label lblID = (Label)DList1.Items[i].FindControl("IDLabel");
Int32 PID = Convert.ToInt32(lblID.ToString();


Only Difference is that
Reply if some confusion.

John Bhatt,
P.Yar.B Complex
 
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