Nagu
Nagu

Reputation: 5114

Working with listbox in winforms (c#)

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?

Upvotes: 1

Views: 1931

Answers (3)

Peter Ramos
Peter Ramos

Reputation: 21

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

Upvotes: 1

Nathan Baulch
Nathan Baulch

Reputation: 20683

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();

Upvotes: 1

pete the pagan-gerbil
pete the pagan-gerbil

Reputation: 3166

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.

Upvotes: 0

Related Questions