I have a ComboBox
which is populated on Page Load event. Just after populating the ComboBox
I call another method which returns a value that I want to make the default value of the ComboBox
when Page loads
. How can I change the selectedIndex
to a value that is returned when I call another method?
XAML for ComboBox
<ComboBox Name="cboProductType" DisplayMemberPath="ProductTypeName" SelectedValuePath="ProductTypeID" SelectedIndex="0"/>
Page Load event:
void OnProductDetailLoad(object sender, RoutedEventArgs e)
{
GetServiceReference.Service1Client service = new GetServiceReference.Service1Client();
service.GetProductDetailsCompleted += service_GetProductDetailsCompleted;
service.GetProductTypeCompleted += service_GetProductTypeCompleted;
service.GetProductTypeAsync();
service.GetProductDetailsAsync(ProductId);
}
Populating ComboBox when Page Loads:
void service_GetProductTypeCompleted(object sender, GetProductTypeCompletedEventArgs e)
{
cboProductType.ItemsSource = e.Result;
}
Calling the other method which returns a particular ProductTypeName
. I tried to get the index of that particular ProductTypeName
but returns -1
always.
void service_GetProductDetailsCompleted(object sender, GetServiceReference.GetProductDetailsCompletedEventArgs e)
{
if (e.Result.Count != 0)
{
p.ProductID = e.Result[0].ProductID;
int index = cboProductType.Items.IndexOf(e.Result[0].ProductTypeName);
cboProductType.SelectedIndex = index;
}
Also is this a right approach for setting the SelectedIndex
property?
Say I have following items loaded in ComboBox
in following Index order:
Index DisplayMemberName(ProductTypeName)
0 Color
1 Size
2 Variant
3 N-size
and e.Result[0].ProductTypeName
contains Variant
so I now want SelectedIndex = 2
of ComboBox
I hope my question is clear
The SelectedIndex
is only valid when you manually fill a combobox. If you are using the ItemsSource
to fill the items in a combobox, you must define a SelectedValuePath
which will then allows you to use the SelectedItem
property to SET/GET the selected item. When using binding to a DataContext
to bind the controls, the SelectedValuePath
should be the property that links the Parent/Child together.