1

Here I need to avoid null from datagridview (winform)

 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");

            }
            
        }

enter image description here

I had try !=string.empty; , !=null; , !=""; but error not solved.

1 == dataGridView1.SelectedRows.Count it true

But

(string)dataGridView1.SelectedRows[0].Cells[0].Value have null value Show error

System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Windows.Forms.DataGridViewCell.Value.get returned null.

Community
  • 1
  • 1
  • You should do `dataGridView1.SelectedRows[0].Cells[0].Value.ToString()` – Chetan May 01 '18 at 04:39
  • `1 == dataGridView1.SelectedRows.Count` that should be on the outer if statement. You need to first check if there is a selected row. `(string)dataGridView1.SelectedRows[0].Cells[0].Value != string.Empty` that is not anymore necessary, unless it is your intention or if there are cases to where it maybe null. – ngeksyo May 01 '18 at 04:42
  • if (dataGridView1.SelectedRows[0].Cells[0].Value.ToString() != string.Empty ) System.NullReferenceException: 'Object reference not set to an instance of an object.' System.Windows.Forms.DataGridViewCell.Value.get returned null. – siddharth Alagesan May 01 '18 at 04:44
  • try this then, (dataGridView1.SelectedRows[0].Cells[0].Value?.ToString() != string.Empty ) – Shivani Katukota May 01 '18 at 05:54

1 Answers1

0

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");
            }
}

is not working it eliminate all even row haveing data