C # datagridview column in array

I create a program with C # and include the datagridview component in it. The datagridview has a fixed number of columns (2) that I want to store on two separate arrays. However, the number of rows varies. How can i do this?

+5
source share
3 answers

Assuming a DataGridView called dataGridView1 and you want to copy the contents of the first two columns into row arrays, you can do something like this:

string[] column0Array = new string[dataGridView1.Rows.Count];
string[] column1Array = new string[dataGridView1.Rows.Count];

int i = 0;
foreach (DataGridViewRow row in dataGridView1.Rows) {
    column0Array[i] = row.Cells[0].Value != null ? row.Cells[0].Value.ToString() : string.Empty;
    column1Array[i] = row.Cells[1].Value != null ? row.Cells[1].Value.ToString() : string.Empty;
    i++;
}
+11
source

Try the following:

ArrayList col1Items = new ArrayList();
ArrayList col2Items = new ArrayList();

foreach(DataGridViewRow dr in dgv_Data.Rows)
{
  col1Items.Add(dr.Cells[0].Value);
  col2Items.Add(dr.Cells[1].Value);
}
+3
source

Jay , . LogArray [0,0], 0, 0.

        // create array big enough for all the rows and columns in the grid
        string[,] LogArray = new string[dataGridView1.Rows.Count, dataGridView1.Columns.Count];

        int i = 0;
        int x = 0;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            while (x < dataGridView1.Columns.Count)
            {
                LogArray[i, x] = row.Cells[x].Value != null ? row.Cells[x].Value.ToString() : string.Empty;
                x++;
            }

            x = 0;
            i++; //next row
        }

, - , , -. , , .

+3
source

All Articles