views:

1365

answers:

1

Hi I'm new to C# and I'm starting to learn how to program I'm learning to program into the Visual Studio Microsoft Edition where I use the WindowsApplication instead of the Console. While trying to make this code, I encountered this command: Selected Index and Selected Item and I would like to know the difference between the two. I'm quite confused now with my code. The code I'm trying to do is adding and deleting text in the listbox.

Thanks for your help.

Additional question: in my code I have this line:

int listBoxSelectedItem = listBox1.SelectedIndex;
listBox1.Items.RemoveAt(listBox1.SelectedIndex);

I would like to understand this part: The first line, has a variable called " listBoxSelectedItem" with a type "int". The position of the item you selected will be store to the variable called "listBoxSelectedItem". Is that correct?

The second line is, the "listBox1.SelectedIndex" is the information that is being pass through to the method, "RemoveAt" Is my understanding here correct?

Thanks

+11  A: 

Selected item will return the object that is selected. Selected index returns the location in the list as an int.

For example you may have a list of strings:

Cat
Dog
Hamster
Horse

If you select "Dog" from this list them the SelectedItem property is the string "Dog" while the SelectedIndex is 1 (indexes are zero based, so the first item is 0, second 1 etc.)

Martin Harris
This is only half the truth. SelectedItem may be an instance of any class and not only strings. The ToString() method is used to tell the box what to display. So you may use any complex object as SelectedItem.
Scoregraphic
@Scoregraphic: How does that contradict what Martin has said? I think this answer is quite accurate. +1
Cerebrus
thanks for the explanation. So that means the selected Items, that's the one you selected in the listbox. And the selected index, tells the position in the list.
tintincute
I also think that what Martin explained is understandable. For me it's clear now;-)
tintincute
@tintincute: Exactly@Cerebrus: I never said Martin is wrong. I just wanted to remark that the SelectedItem may be of any type.
Scoregraphic
thanks Scoregraphic:-) I also didn't say that you're wrong. I just wanted to affirm what Cerebrus said. I think it's clear now;-)Thanks again
tintincute