-4

I'm beginner and I have small problem. I need check if it is not empty die combobox. Now when I click button and the Combobox give an null error

"An unhandled exception of type 'System.NullReferenceException' occurred in WindowsFormsApplication4.exe

Additional information: Object reference not set to an instance of an object.

 private void Wykonaj_Click(object sender, EventArgs e)
        {           

        if (Combobox1.SelectedIndex.ToString() != null)
        {
            if (Combobox.SelectedItem.ToString() != "Audi")
            {
                wersja= "110";
            }
            else
            {
                wersja = "101";
            }
        }
    }
demonplus
  • 5,036
  • 11
  • 41
  • 56

3 Answers3

1

You have mistake in typing. Replace

if (Combobox.SelectedItem.ToString() != "Audi")

with

if (Combobox1.SelectedItem.ToString() != "Audi")
Nenad J.
  • 136
  • 1
  • 7
1
string wersja = string.Empty;
if(Combobox.SelectedIndex > 0)
{
    if (Combobox.SelectedItem.ToString() != "Audi")
    {
        wersja= "110";
    }
    else
    {
        wersja = "101";
    }
}
Joris van Roy
  • 143
  • 1
  • 1
  • 11
  • While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – kayess Dec 20 '16 at 14:40
1

In your case either Combobox.SelectedItem or Combobox1.SelectedItem is null If they are different comboboxes. In c# null.ToString() throws NullReferenceException which means if that value is null means definitely exception will thrown. I would like to suggest you to use like this:

if (Combobox1.SelectedIndex >= 0)
{
    if (Combobox.SelectedItem != null && Combobox.SelectedItem.ToString() != "Audi")
       wersja = "110";
    else
       wersja = "101";
}

Here you are checking for null and if it is not null then check its value with "Audi"

Rob
  • 25,569
  • 15
  • 73
  • 87
sujith karivelil
  • 26,861
  • 6
  • 46
  • 76
  • Thanks you !! The solution was "if (Combobox.SelectedIndex >= 0)" – Mariusz Nazwiskoo Dec 20 '16 at 18:32
  • @un-lucky You've been here long enough to know this question has been duplicated *many* times before. Please flag such questions as duplicates rather than providing tailored answers to each. Thanks! – Rob Dec 21 '16 at 01:58
  • 1
    I was not the First one to answer this question, When I saw the questions 2 answers ware already posted here and are confusing and not clear enough, That's why I have answered, forgive me if it is wrong, anyway Thanks for your comment @Rob – sujith karivelil Dec 21 '16 at 02:11