Default Text in the Drop Down

1k views Asked by At

I am working on a wpf application, when using Combo Box control i am assigning ItemsSource to it. So, it displays a list of items with no item selected, now user can select an item of his choice. When user has made a selection he has no option to undo that. I want him to be able to get the initial state where no item is selected. How can i do that?

3

There are 3 answers

2
Joshua Cauble On BEST ANSWER

There are multiple ways that would also be similar in windows forms programming. You could do either of the following:

1) Add a blank or --None-- record to your combobox datasource that is the default record. 2) You could monitor the keypress event and say use the ESC key to reset the selected index back to -1.
3) If your combobox allows typing you could also allow them to clear the text and onleave if the text field is blank set the selectedindex back to -1 so that it does not get reset to the selected value.

Alot of the time my users prefer option 1 but that's my users.

That should give you some options.

0
MoominTroll On

I'd go for resetting back to a --None-- record over the default blank record (with an index of -1) every time. If you're handling events for "selection changed" or something on the ComboBox then you risk getting null-reference errors if you point the box at -1, and it's just as easy since the only change you'd have to make is set the selected index to (say) 0 rather than -1.

myComboBox.SelectedIndex = 0; //where 0 is a given default content entry.
0
Robert Rossney On

Generally speaking, I find that if I need to add complexity to a WPF application, adding it to the data source is more robust than adding it to the XAML.

In your example, I'd fix this in my data source. If I have:

public IEnumerable<Person> People { get {...} }

in my data source, I'd add this:

public IEnumerable<Person> PeopleWithNull
{
   get
   {
      return (new List<Person> { null }).Concat(People);
   }
}