我在布局中声明了一个DataGridView(名为dataGridView1)。我想要获得的单元格值是单元格中组合框选择的结果。基于这两个链接:MSDN和SO Post,我的代码如下所示:
private void Submit_Click(object sender, EventArgs e)
{
//output data to ResultsText richtextbox to check it
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
ResultsText.Text +="\n"+ cell.Value.ToString();// getting null reference exception here
}
}
}
我的DataGridView代码实现:
private void PopulateDataGridView()
{
dataGridView1.AutoGenerateColumns = false;
DataTable dt = new DataTable();
dt.Columns.Add("LoadCaseCol");
DataGridViewComboBoxColumn lc = new DataGridViewComboBoxColumn();
lc.DataSource = new List<string>() { "opt1", "opt2", "opt3", "opt4" };
lc.HeaderText = "Select Load Cases";
//lc.DataPropertyName = "Money";
//DataGridViewTextBoxColumn name = new DataGridViewTextBoxColumn();
//name.HeaderText = "Name";
//name.DataPropertyName = "Name";
dataGridView1.DataSource = dt;
//dataGridView1.Columns.AddRange(name, money);
dataGridView1.Columns.AddRange(lc);
}
答案 0 :(得分:1)
要避免使用NullReferenceException
:
ResultsText.Text +="\n"+ (cell.Value == null ? "NULL" : cell.Value.ToString());
而不是
ResultsText.Text +="\n"+ cell.Value.ToString();
(假设这是问题)。
<强>已更新强>
由于代码初始化组合框列,可能会出现此问题。
请尝试设置DataPropertyName
:
private void PopulateDataGridView()
{
dataGridView1.AutoGenerateColumns = false;
DataTable dt = new DataTable();
dt.Columns.Add("LoadCaseCol");
DataGridViewComboBoxColumn lc = new DataGridViewComboBoxColumn();
lc.DataSource = new List<string>() { "opt1", "opt2", "opt3", "opt4" };
lc.HeaderText = "Select Load Cases";
lc.DataPropertyName = "LoadCaseCol";
dataGridView1.DataSource = dt;
dataGridView1.Columns.AddRange(lc);
}
答案 1 :(得分:1)
当您致电NullReferenceException
时cell.Value
null
为ToString()
,您将获得Convert.ToString()
。
您可以使用null
来专门检查var sb = new StringBuilder();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
sb.AppendLine(Convert.ToString(cell.Value));
}
}
ResultsText.Text = sb.ToString();
并将其转换为空字符串(防止抛出异常):
{{1}}