JEricaM JEricaM - 2 years ago 375
C# Question

Insert datagridview column values into an Array c#

In my form I have this DataGridView (grid1), filled from a sqllite database.
enter image description here

I want select the column with the name "cap" and insert the column's values into an array.
How can I do?

  1. I don't find a way to select the column cap by name, so I decided to indicate it with the index, but I don't like this way..

  2. I don't know ho to insert these values into an array. there are a lot of columns/cell method but I don't figured out which one can help me!

I tryed to do this way (from an old answer here in the site) but it gives me error of "out of bounded matrix"

int[] wareCap = new int[grid1.Rows.Count];
//How I filled my dgv, if this can help
var context = new ForliCesenaEntities2();
BindingSource bi1 = new BindingSource();
bi1.DataSource = context.warehouses.ToList();
grid1.DataSource = bi1;

//How I try to insert the values into int[] wareCap
for (int i = 0; i<(grid1.Rows.Count-1); i++)
wareCap[i] = Convert.ToInt16(grid1.Rows[i].Cells[1].Value);

Thanks in advice

Answer Source

First you gridview has to be filled with values, then:

List<int> intValues = new List<int>();
foreach (DataRow row in grid.Rows)

int[] array = intValues.ToArray();

should do the trick.

Alternatively, you could use LINQ.

int[] intArray = dataGridView1.Rows
                .Select(row => int.Parse(row.Cells["cap"].Value.ToString())).ToArray();


The above solution might crash if the DataGridView's AllowUserToAddRows property is set to true. Because in that case your last row is the row for entering a new record, the Value is null, so invoking the ToString method on it causes a NullReferenceException.

I see two possibilities:

  • set your datagridview's AllowUserToAddRows property to false (but the user won't be able to add new rows),
  • use the following solution

Check if the row is the row for entering a new record:

int[] intArray = dataGridView1.Rows
                .Where(row => !row.IsNewRow)
                .Select(row => Convert.ToInt32(row.Cells["cap"].Value.ToString())).ToArray();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download