C#datagridview列成一个数组

Xed*_*ire 5 .net c# arrays datagridview

我正在用c#构建一个程序,并在其中包含了一个datagridview组件.datagridview具有固定数量的列(2),我想将其保存到两个单独的数组中.但行数确实发生了变化.我怎么能这样做?

Jay*_*ggs 11

假设一个名为dataGridView1的DataGridView并且您希望将前两列的内容复制到字符串数组中,您可以执行以下操作:

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++;
}
Run Code Online (Sandbox Code Playgroud)


Abe*_*ler 4

尝试这个:

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);
}
Run Code Online (Sandbox Code Playgroud)