|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Setting Combobox Default Selection
I have a combobox with one or more options, when the user makes a selection the SelectedIndexChanged event is called, and a datagrid is populated with data depending on what was selected.
My problem is that by default when the window loads the first item is selected in the combobox, but the event never fires. I can manually set a value in the constructor, such as SelectedIndex = 0, but this never fires the event either, whereas SelectedIndex = 1 or greater will cause the event to trigger. However sometimes there may only be a single entry in the list, and id rather select the first item than the second! How can I ensure that when the form loads a value is selected and the SelectedIndexChanged event triggers? Thanks in advance! |
|
#2
|
|||
|
|||
|
Put this in your forms's Load event:
Code:
yourcombobox.SelectedIndex = 0 That should do it. Last edited by Raytheon : May 6th, 2008 at 08:31 PM. |
|
#3
|
|||
|
|||
|
Quote:
Hi Raytheon, looks like I screwed up my original post - that is the value I tried to set, NOT SelectedValue - however while it works for position 1 and greater, it doesnt work when you select the first item in the list. |
|
#4
|
||||
|
||||
|
How are you populating the ComboBox?
__________________
Joel B Fant "An element of conflict in any discussion is a very good thing. Shows everybody's taking part, nobody left out. I like that." .NET Must-Haves Tools: Reflector References: Threading in .NET |
|
#5
|
|||
|
|||
|
Quote:
The combobox is populated from a DataTable, by assigning the the table to datasource. |
|
#6
|
||||
|
||||
|
One option is to call combobox.BeginUpdate() and use a foreach loop to populate the Items collection yourself, then make a selection (or not) manually, then finally call combobox.EndUpdate(). This way, no automatic selection is made for you, as happens with assigning to combobox.DataSource.
Another option is to remove EvenHandlers from the SelectedIndexChanged event, assign the data, make sure nothing is selected, and then restore the EventHandlers. Code:
C#
comboBox1.BeginUpdate(); comboBox1.SelectedIndexChanged -= comboBox1_SelectedIndexChanged; comboBox1.DataSource = data; comboBox1.SelectedIndex = -1; // OR comboBox1.SelectedItem = null; comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged; comboBox1.EndUpdate(); |
![]() |
| Viewing: Dev Shed Forums > Programming Languages - More > .Net Development > Setting Combobox Default Selection |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|