【发布时间】:2018-05-02 12:45:24
【问题描述】:
这里我需要避免 datagridview (winform) 中的 null
private void SendUpdate()
{
if ((string)dataGridView1.SelectedRows[0].Cells[0].Value != string.Empty )
{
if (1 == dataGridView1.SelectedRows.Count)
{
int Id = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[0].Value);
Update up = new Update();
up.AssignValue(Id);
up.textBox1.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
up.comboBox1.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
up.textBox2.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
up.textBox3.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
up.textBox4.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
up.textBox5.Text = dataGridView1.SelectedRows[0].Cells[6].Value.ToString();
up.ShowDialog();
}
else
{
MessageBox.Show("Please Select the Single Data Which Required to Update");
}
}
else
{
MessageBox.Show("You Select the empty Row");
}
}
我试过!=string.empty;,!=null;,!="";
但错误没有解决。
1 == dataGridView1.SelectedRows.Count是真的
但是
(string)dataGridView1.SelectedRows[0].Cells[0].Value 有空值
显示错误
System.NullReferenceException: '对象引用未设置为对象的实例。'
System.Windows.Forms.DataGridViewCell.Value.get 返回 null。
【问题讨论】:
-
你应该这样做
dataGridView1.SelectedRows[0].Cells[0].Value.ToString() -
1 == dataGridView1.SelectedRows.Count应该在外部 if 语句中。您需要首先检查是否有选定的行。(string)dataGridView1.SelectedRows[0].Cells[0].Value != string.Empty不再需要,除非这是您的意图,或者在某些情况下它可能为空。 -
if (dataGridView1.SelectedRows[0].Cells[0].Value.ToString() != string.Empty) System.NullReferenceException: '对象引用未设置为对象的实例。' System.Windows.Forms.DataGridViewCell.Value.get 返回 null。
-
那么试试这个,(dataGridView1.SelectedRows[0].Cells[0].Value?.ToString() != string.Empty)
标签: c# visual-studio-2012