Click here to Skip to main content
16,018,057 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What i have to check i am getting exception on datakey of a gridview that its getting nul value..

gridview is properly displaying data.. why my code is not getting data key??

here is the code

C#
if (DropDownList1.Text == "Completed")
     {
         for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
         {
             GridViewRow row = GridView1.Rows[i];
             if (row.RowType == DataControlRowType.DataRow)
             {
                 ShoppingCartItem item = new ShoppingCartItem();

                 item.ProductID = (int)GridView1.DataKeys[i].Value; //I am getting index out of range exception here..
                 item.Quantity = int.Parse(((Label)(row.FindControl("txtmainqty"))).Text);





                 dbcon db1 = new dbcon();
                  int orderedQuantity = System.Convert.ToInt32(item.Quantity);

                  string query1 = "update Products set productquantity=productquantity-'" + orderedQuantity + "' where ProductID='" + item.ProductID + "'";
                  //bool b = db.UDI(query);
                  bool c = db1.UDI(query1);
                  if (c == true)
                  {

                     // lblshow.Text = "Product Delivered and Added to DataBase Sucessfully";

                  }

                  else
                  {
                      //lblshow.Text = " Operation Not successful";

                  }

i have no proble with the gridview i have done this in another page.. buts its no working on my current page.. y datakey is giving index out of range exception..
Posted
Comments
Sriram Chitturi 9-Feb-12 18:48pm    
Can you provide the GridView1 markup on the page?
Also what is the event when this code is called?

1 solution

Please check whether you have set the DataKeyNames property of GridView to the required field of the data. Because the program creates DataKey objects after setting the DataKeyNames property and the DataKey object contains the values of the fields specified in the DataKeyNames property. If you have not set DataKeyNames property, you may get index out of range exception when you access elements of DataKeys collection.
 
Share this answer
 
v2
Comments
ProEnggSoft 10-Feb-12 20:08pm    
Thank you for accepting the solution

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