C# 根据datagridview 已有的列名去添加数据
假设datagridview的名称为dataGridView1,已有的列名为columnName1和columnName2,可以按照以下代码进行添加数据:
// 添加第一行数据
dataGridView1.Rows.Add();
int rowIndex = dataGridView1.Rows.Count - 1; // 获取当前行号
dataGridView1.Rows[rowIndex].Cells["columnName1"].Value = "数据1";
dataGridView1.Rows[rowIndex].Cells["columnName2"].Value = "数据2";
// 添加第二行数据
dataGridView1.Rows.Add();
rowIndex = dataGridView1.Rows.Count - 1;
dataGridView1.Rows[rowIndex].Cells["columnName1"].Value = "数据3";
dataGridView1.Rows[rowIndex].Cells["columnName2"].Value = "数据4";
在上述代码中,首先通过dataGridView1.Rows.Add()添加了一行空数据,并通过dataGridView1.Rows.Count - 1获取了当前行的行号rowIndex。然后通过dataGridView1.Rows[rowIndex].Cells[columnName1].Value = "数据1"的方式,将数据1添加到了columnName1这一列中。同理,将数据2、数据3和数据4添加到了columnName2这一列中
原文地址: http://www.cveoy.top/t/topic/hv4z 著作权归作者所有。请勿转载和采集!