Saturday, August 6, 2011

Setting SelectedValue for ComboBox

             When you add combobox items inside xaml then SelectedValue of the Combo Box didn't work.

          When I come across this problem I have search alot on net and then I found solution regarding the selectedValue selected in code behind when you have added item of the ComboBox within the xaml. We have used the Items Source property of the combo box and then bind the set the SelectedValue. Now solution for the problem  which I have mentioned is quite simple. For the sample test application I have two combo box one which is set normal and will not work is added first and then the second one which is work when setting the SelectedValue. You can see the layout of the screen in Image 1.

Image 1

The code for both the combo Box are given in the List 1. Here you can see that I have text block control with each of the combo box control. The main point which you have to notice in both the combo box control is that you can see in the second combo Box I have set the DisplayMemberPath and SelectedValuePath of the combo box to Content.

List 1
The code for the Set Value button is shown in the List 2. here you can see that I have set the SelectedValue as string "Male" for both the cboNotworking and cboWorking combo box control but the selected value is shown only for the cboWorking combo box as I have set the DisplayMemberPath and SelectedValuePath to the Content for the cboWorking combo box not for the cboNotWorking combo box.

List 2

I think you can solve the problem when you have similar situation like I have in during my project development.You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!


Raja Yellapu said...

Coool article dude !!!! It Worked

Asim Sajjad said...

@Raja Yellapu: thanks for your comments. and glad to hear that it works for you.

Fun Chiat said...

It took me 2 hours and lucky for your post. If wasn't your simple combo box content example, I nearly resort to code behind (gave up!)