Datagridview返回System.NullReference例外
本文关键字:例外 NullReference System 返回 Datagridview | 更新日期: 2023-09-27 18:06:31
这段代码给了我一个消息框:"System. " 这个解决方案来自我的另一个问题,但行不通。也许有人知道,错误藏在哪里?
private void button1_Click(object sender, EventArgs e)
{
try
{
//Setup list object
var llist = new List<MyClass>();
//Loop through datagridview rows
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var obj = new MyClass()
{
Datum = row.Cells["Datum"].Value.ToString(),
Nachricht = row.Cells["Nachricht"].Value.ToString()
};
llist.Add(obj);
}
//Write out JSON file
string export = JsonConvert.SerializeObject(new { types = llist }, Formatting.Indented);
File.WriteAllText(@"C:'test'upload" + "''" + "export.json", export);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public class MyClass
{
public string Datum { get; set; }
public string Nachricht { get; set; }
}
正如我在评论中已经说过的,在从单元格中读取值之前添加null
检查。
//Setup list object
var llist = new List<MyClass>();
//Loop through datagridview rows
foreach (DataGridViewRow row in dataGridView1.Rows)
{
// ------------------ changed code ----------------------
string datNum = null; // by-default we say it will be null
string nachricht = null; // same with other field
// now we will check if cell does NOT have a null value
if (row.Cells["Datum"].Value != null)
// then we will put it in a variable
datNum = row.Cells["Datum"].Value.ToString();
// similarly for other variable as well
if (row.Cells["Nachricht"].Value != null)
nachricht = row.Cells["Nachricht"].Value.ToString();
var obj = new MyClass()
{
Datum = datNum,
Nachricht = nachricht
};
// ------------------------------------------------------
llist.Add(obj);
}