Click here to Skip to main content
15,906,467 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i got a combobox store list of item ( not using data bound ), a button used to clear all of the text of combobox and textbox, with a few textbox

when i press on the clear button, it show me this error message :

An unhandled exception of type 'System.NullReferenceException' occurred in bookbar user interface.exe

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

What I have tried:

this is my code

code for my button :

private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
            textBox2.Clear();
            comboBox1.SelectedIndex = -1;
        }


i also set some code in the event of combobox, SelectedIndexChanged, this is where the error message show

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
            if (comboBox1.SelectedItem.ToString() != "Lain-lain") { // < error in this line
                textBox1.Clear();
            }
            else  {
                textBox1.Enabled = true;
            }
            updatebooknameList();
        }
Posted
Updated 10-Sep-18 22:04pm
v2

1 solution

If you debug your code and put a breakpoint on the line where the exception is thrown, you will discover that the SelectedItem property of comboBox1 is null.

You need to check for it being null before you issue the .ToString()
 
Share this answer
 
Comments
newbie1992 11-Sep-18 20:30pm    
thanks!
CHill60 12-Sep-18 3:37am    
No problem!
For the record, it's a very common error - just about everybody has done this at some time :-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900