对于DataGridView,如何从每行获取值?

ski*_*kid 7 c# datagridview winforms

我想知道在datagridview中遍历所有行并从单元格中获取值的最佳方法是什么.
这是我在想的事情,但我不是很喜欢它,因为如果我重新排列列,那么代码也必须改变.

for (int i = 0; i < dataGridView.RowCount; i++)
{
   string Value0 = dataGridView1.Rows[i].Cells[0];
   string Value1 = dataGridView1.Rows[i].Cells[1];
   string Value2 = dataGridView1.Rows[i].Cells[2];
}
Run Code Online (Sandbox Code Playgroud)

CAb*_*ott 11

您可以使用a foreach来迭代其中的DataGridViewRows DataGridView并使用列名从以下位置检索值Cells:

foreach (DataGridViewRow dr in dataGridView.Rows)
{
    string col1 = dr.Cells["Col1"].Value.ToString();
    string col2 = dr.Cells["Col2"].Value.ToString();
    string col3 = dr.Cells["Col3"].Value.ToString();
}
Run Code Online (Sandbox Code Playgroud)