[英]C# How to read all the data in a datagridview and put it in a listbox?
我想在单击按钮时从 datagridview 读取所有数据,然后将其放入列表框中。 我走了这么远,但每次都行不通,我不知道为什么。 我已经尝试了一切
这是我的代码:
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
DataGridViewCell c = dataGridView1.Rows[i].Cells[j];
if (c.Value != null)
{
listBox1.Items.Add(c.Value.ToString());
}
}
我收到以下错误:“未将对象引用设置为对象的实例”
异常是在“字符串数据”行抛出。
我猜您DataGridView
中的值之一的值为null
。 当您尝试对属性Value
调用ToString()
方法时:
string data = dgvOverzicht.Rows[getal - 1].Cells[i].Value.ToString();
它抛出异常。
解决此问题的一种方法是检查Value
是否为null
,如果不是,则继续调用ToString()
方法:
int getal = 0;
for (int i = 1; i < 10; i++)
{
getal++;
DataGridViewCell c = dgvOverzicht.Rows[getal - 1].Cells[i];
if (c.Value != null)
{
listBox1.Items.Add(c.Value.ToString());
}
}
编辑:
您使用的 for 循环只会访问网格的对角线。 如果要获取所有单元格,则需要 2 个 for 循环:
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
DataGridViewCell c = dataGridView1.Rows[i].Cells[j];
if (c.Value != null)
{
listBox1.Items.Add(c.Value.ToString());
}
}
}
如果您只有 4 列,您的代码将获得 nullreferenceexception
您使用变量 i 来决定单元格,但 i 可以是 1 到 9,因此如果 datagridview 不包含足够的单元格,则会发生错误。
希望这可以帮到你。
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 3; i++)
{
dataGridView1.Rows.Add("0", "1", "2", "3");
}
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
listBox1.Items.Add(dataGridView1.Rows[i].Cells[j].Value.ToString());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.