Click here to Skip to main content
16,015,755 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi every body
i work on winform application and want to fill a datagridview with specific columns of datatable and add a column named barcode item. the first column is for item no, the second column is filled with barcode generated from Item no and the third column is for item name. the first loop running good, but with the second loop it throwing exception when fill the second row in datagridviw. here is the code

so what is the problem and the solution

What I have tried:

try
     {
             SqlCommand cmdss1 = new SqlCommand("usp_Get_All_Item", cn);
             cmdss1.CommandType = CommandType.StoredProcedure;



             cmdss1.Parameters.Clear();



             SqlDataAdapter SQss1 = new SqlDataAdapter(cmdss1);
             DataTable dtss1 = new DataTable();
             SQss1.Fill(dtss1);
             if (dtss1.Rows.Count > 0)
             {

                 for (int i = 0; i <= dtss1.Rows.Count - 1; i++)
                 {


                     string ssqs1 = dtss1.Rows[i]["Item_No"].ToString();
                     string ssqs2 = dtss1.Rows[i]["Item_Name"].ToString();

                     string s = ssqs1;


                     Image m1 = BarcodeLib.Barcode.DoEncode(BarcodeLib.TYPE.CODE39, s, true, Color.Black, Color.White, 1200, 1200);

                     dataGridView1.Rows[i].Cells[0].Value = ssqs1;
                     dataGridView1.Rows[i].Cells[1].Value = m1;
                     dataGridView1.Rows[i].Cells[2].Value = ssqs2;



                 }



             }
     }
     catch (Exception ex)
     {
          MessageBox.Show(ex.ToString());
     }
Posted
Updated 23-Jan-17 8:42am
Comments
[no name] 23-Jan-17 14:34pm    
First thing is that you expect us to guess what the exception is?
Mohamed El-Wehishy 23-Jan-17 14:50pm    
no
i am so sorry for that
here is the exception
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

1 solution

You don;t appear to add any rows to your datagridview: so when you try to set values you are almost certainly running out of rows and an exception is the result. Useing an index does not create a new row - you have to do that explicitly with the DataGridView.Rows.Add method.
 
Share this answer
 
Comments
Mohamed El-Wehishy 23-Jan-17 14:56pm    
thanks very much for your help
OriginalGriff 23-Jan-17 15:14pm    
You're welcome

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