1

I am adding data in datagridview dynamically in page load event. But I am getting an error that says that the index was out of range. ("Must be non-negative and less than the size of the collection.parameter name in datagridview.")

The following is the code:

        dataGridView1.Rows.Add();

        dataGridView1.Rows[0].Cells[0].Value = "Basic";
        dataGridView1.Rows[0].Cells[1].Value = "Basic";
        dataGridView1.Rows[1].Cells[0].Value = "PDALLW";
        dataGridView1.Rows[1].Cells[1].Value = "Professional Development Allow";
        dataGridView1.Rows[2].Cells[0].Value = "BPAllw";
        dataGridView1.Rows[2].Cells[1].Value = "Business Promotion Allowance";
Holger Brandt
  • 4,324
  • 1
  • 20
  • 35
Maddy
  • 33
  • 2
  • 13
  • You use 3 rows here, but add only one. Maybe it's the problem? – Iarek Aug 09 '12 at 13:11
  • This is a good link for binding to the DataGrid. http://stackoverflow.com/questions/5809816/datagrid-binding-in-wpf – Omzig Aug 09 '12 at 13:13

3 Answers3

1

Your grid does not have rows. You must not have binded it or you are exceeding the rows it has got.

  1. Make sure you bind the grid before you access its rows.

  2. Make sure you do not access the row index which is not present.

Adil
  • 146,340
  • 25
  • 209
  • 204
1

You seem to add only one row. Therefore you can only access row 0. Calls like dataGridView1.Rows[1] and dataGridView1.Rows[2] will fail unless you create three rows.

Explanation:

dataGridView1.Rows.Add();

This adds a row to the DataGridView. So you have one row with index 0 (row indexes start at 0). You can set values for row 0 as you have done:

dataGridView1.Rows[0].Cells[0].Value = "Basic";

But then you try setting values to row with index 1 (second row) :

dataGridView1.Rows[1].Cells[0].Value = "PDALLW";

This will fail because you have only added one row (called Rows.Add once). If you want three rows, call dataGridView1.Rows.Add(); three times, before setting cell values.

Meta-Knight
  • 17,626
  • 1
  • 48
  • 58
  • i dont understand please explian me – Maddy Aug 09 '12 at 13:16
  • I've added a detailed explanation. – Meta-Knight Aug 09 '12 at 13:21
  • if i have 100 rows than i need to add dataGridView1.Rows.Add(); 100 times its bad effect. is there any solution if i have 100 rows – Maddy Aug 09 '12 at 13:24
  • Usually when you have so much data, it is typically stored in a database. So instead of adding rows one by one, you load data from the database, loop through each row, and the instructions to add a new row and populate cell values only appear once, inside the loop. – Meta-Knight Aug 09 '12 at 13:29
1

Call Add(3) instead of Add(). You could also extend this to add as many rows as needed at any given time. MSDN Link

steveg89
  • 1,807
  • 2
  • 15
  • 29
  • thanks it works .i need to ask one question that i want to add two radio button on every single row how can i do that? – Maddy Aug 09 '12 at 13:34