Click here to Skip to main content
15,886,833 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

This related to a question from earlier I asked and was answered by the mighty Griff!

I can now get the item wanted in the list box sorted out from the horrible list, I need to auto select it now so I can parse it properly, I have tried:
C#
 lstMeters.SelectedItem = 0;
SelectedMeter = lstMeters.SelectedItem.ToString();
However this doesn't work (?) is it due to the fact that there is only one item in the list box? the above would select the item if there was more than one item.
Glenn
Posted

1 solution

If you are looking to set the initial selection, you should try using SelectedIndex. SelectedItem is an object type property it would return the actual object that is bound to the control.

Assuming it is a windows form, following works fine for me:

C#
listBox1.Items.AddRange(new string[] { "1", "2", "3" });
            //listBox1.SelectedItem = "1";
            listBox1.SelectedIndex = 0;

            string str = listBox1.SelectedItem.ToString();


You can uncomment SelectedItem line and comment SelectedIndex line and that would work fine too.
 
Share this answer
 
v2
Comments
glennPattonWork3 14-May-14 7:16am    
Tried it, doesn't work!, what I am aiming to is not have to click on the one item in the listBox to 'high light' it. I just need to auto select it!!
dan!sh 14-May-14 7:19am    
Updated the reply.
glennPattonWork3 14-May-14 7:27am    
Thanks for that, I was close!
Glenn

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