[英]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.