views:

323

answers:

3

Hi, How can i add 10 items to listbox dynamically to a listbox and after that I want to show the selected item value in click event of list box.

I tried like this

for(int i=1;i<10 ;i++)
{
mylistbox.Items.Add(i.ToString());
}

in click event handler

MessageBox.Show(mylistbox.SelectedValue.ToString());

it is showing error.

Whats the wrong with this?

A: 

Dmitriy has it exactly.

A good way to check what is happening when you're debugging is to highlight 'mylistbox.SelectedValue' and right-click, then select 'Add Watch'. You can then track the value of that property in the Watch window.

You can do this with any variable, and any time it shows null and you're trying to use that value you know it will throw a Null Reference Exception.

It's also good for picking up letters in a string you're trying to convert to an integer, and other similar "d'oh!" moments.

pete the pagan-gerbil
+1  A: 

Try using the SelectedItem property instead.

SelectedValue only works when you fill the ListBox with objects and have a ValueMember assigned. Here is a minimal example:

var mylistbox = new ListBox {Dock = DockStyle.Fill};
mylistbox.Click += (sender, e) =>
                   MessageBox.Show(mylistbox.SelectedItem.ToString());
for (int i = 1; i < 10; i++)
{
    mylistbox.Items.Add(i.ToString());
}
new Form {Controls = {mylistbox}}.ShowDialog();
Nathan Baulch
Thank you, my answer wasn't correct.
Dmitriy Matveev
A: 

use the following code on the click handler

MessageBox.Show(mylistbox.Text.ToString()); //This will show the selected item as your requirement.

replace the .SelectedValue with .Text

Peter Ramos