0

I want to insert null parameter in some values, but I get the following error :

System.NullReferenceException: 'Object reference not set to an instance of an object.' System.Windows.Forms.ListControl.SelectedValue.get returned null.

The program is a Windows Forms application, and the code is as follows:

using (var context = new SamenEntities())
{
    person ppp = new person()
    {
        id = textBox1.Text.Trim(),
        name = textBox2.Text.Trim(),
        family = textBox3.Text.Trim(),
        birth_date = dateTimePicker1.Value,
        birth_provice = Convert.ToInt32(comboBox1.SelectedValue.ToString()),
        note = richTextBox1.Text.Trim(),
        img_personal = ImageToByteArray(pictureBox1.Image),
        date_register = DateTime.Now
    };

    context.persons.Add(ppp);
    context.SaveChanges();
}

How to enter null value or enter default value from SQL server?

Kzrystof
  • 5,441
  • 7
  • 34
  • 77
  • What are the fields you're trying to set as `null`? – Pietro Nadalini Aug 29 '18 at 22:18
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – mjwills Aug 29 '18 at 22:19

1 Answers1

1

By look at the exception, it says that the ComboBox does not have any value selected. It is not about SQL Server not accepting null at this point.

With that information, you should check that one value is selected, meaning it is not null, like this:

object selectedValue = comboBox1.SelectedValue;

if(selectedValue != null)
{
    ppp.birth_provice = Convert.ToInt32(selectedValue.ToString()),
}

On top of that, you may want to consider using Int32.TryParse to make sure the selected value is an actual integer.

Kzrystof
  • 5,441
  • 7
  • 34
  • 77