【问题标题】:How avoid error when get null from datagraidview从datagradview获取null时如何避免错误
【发布时间】: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


【解决方案1】:

https://stackoverflow.com/a/32390609/9543244

 private void SendUpdate()
        {

            if (String.IsNullOrWhiteSpace(dataGridView1.SelectedRows[0].Cells[0].Value as string))
            {
                MessageBox.Show("You Select the empty Row");
            }
}

不工作 它消除了所有具有数据的偶数行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2012-10-05
    • 2021-07-02
    • 2018-07-30
    • 2020-01-17
    • 2014-05-27
    相关资源
    最近更新 更多