Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Object reference not set to an instance of an object.

Status
Not open for further replies.

Westond

Programmer
Jan 19, 2005
43
0
0
US
What causes this error? Here is an example that will cuase it.

I have a listbox and when someone clicks on a entry in the listbox I tried to do:

string x;

x = listbox1.SelectedValue.ToString();

I am tring to understand the general rule on this because I come across it alot.

Thanks for any input!
 
Code:
		private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
		{
			string x;

			x = listBox1.SelectedItem.ToString();
			MessageBox.Show(x);

		}

works.

SelectedValue refers to the ValueMember property (usually used in conjunction with the DisplayMember and DataSource properties). If for example to have a table with and index field and a description field. You assign the table as the DataSource, the description field as the DisplayMember and the index field as the ValueMember.


Hope this helps.

[vampire][bat]
 
This error will occur when SelectedValue doesn't exist (the user has not selected an item yet)

so when you ask it to go .ToString() you are asking null to convert itself.

I would check for null first

if (listBox1.SelectedValue != null)
{
//do your stuff.
}


Also: Why use a listbox? They are antiquated. You are better off to use a ListView which acts much like a listbox but has a bit more flexibility.
 
JurkMonkey, that will prevent the error - but still will not return a value unless .ValueMember as been assigned. Selecting an item does not in itself provide a value for .SelectedValue.


Hope this helps.

[vampire][bat]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top