Click here to Skip to main content
15,880,427 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If there is drop downlist with only one item ( a string ) is available in it, I dont want the user go click the drop down list and choose the item, instead I want the item to be selected autamatically when i run the code. I tried many times nothing works . what is the right c# code which can do it in asp.net.
Posted

1 solution

Put this in your constructor AFTER the call to InitializeComponents, or in the form's
Load
event handler

C#
combobox.SelectedIndex = n;


where "n" is the index number of the item you want to automatically select.
 
Share this answer
 
Comments
pratheep7 2-Sep-11 11:18am    
Could you show me the c# code which does the work because I don't understand what you have just mentioned. i'm in the learning process.
GParkings 2-Sep-11 11:43am    
that is the c# code :D . The comboBox control (here 'combobox' is the instance name of your combo box control) exposes a property called selected index, when that index is set it finds the entry within the combobox at that index (position) and selectes it. (positions start at 0 by the way).

When your application goes to display your form it first 'constructs' it, at which point the forms constructor method is called, and then displays it, at which point the load event is fired which executes the code in the load event handler. Therefore placing the above code in either of those 2 locations will cause the item within the combobox at the index (position) defined as n (in other words replace 'n' with a number) to be selected.

If you wish to only select an entry in the combobox when it has exactly 1 entry i its list of items you want:

if(combobox.Items.Count == 1)
{
combobox.SelectedIndex = 0;
}

which will select the first item if it is the only item
RaviRanjanKr 2-Sep-11 16:12pm    
Nice Answer John, My 5+

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