I have the DataTable with following columns:
id, Name, Description, ParentId
and would like to create a WPF control (.NET 4.0 framework) which implements a combobox which displays the names which are bound to values of id. So when the user selects a name displayed in the combobox the behind logic has to retrieve its id value.
I would be very thankful if anyone could show the way of doing the described above.
This article shows how to bind data dynamically from the database and get the ComboBox selected Text and Value. In ComboBox Element set the attribute ItemSource="{Binding}". Here DisplayMemberPath helps to display Text in the ComboBox. SelectedValuePath helps to store values like a hidden field.
You have to bind the myTable. DefaultView or IEnumerable from myTable. AsEnumerable(). The ItemsSource can also be set in XAML: ItemsSource="{Binding myProperty, Mode=OneWay}".
Tables[0]; cbMissAtt. DisplayMember = "value"; cbMissAtt. ValueMember = "text"; this should show the values under value column unless you have a problem with your dataset code.
Like so:
In your XAML file, put:
<ComboBox x:Name="myComboBox" DisplayMemberPath="Name" SelectedValuePath="id" />
In your code behind, put:
myComboBox.ItemsSource = myTable;
(myTable being a reference to the table you mentioned)
Then you can reach the id of the currently selected person in the combo box using the expression:
NameComboBox.SelectedValue
MVVM pattern solution
XAML:
<ComboBox
x:Name="myComboBox"
DisplayMemberPath="Name"
SelectedValuePath="id"
ItemsSource="{Binding myDataTable}"
SelectedValue="{Binding theID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
>
"Name" and "id" are columns in myDataTable.
Code behind:
private MyViewModel _myViewModel = new MyViewModel();
this.DataContext = _myViewModel;
MyViewModel class
public DataTable myDataTable { get; set; }
public short theID { get; set; }
The selected value (row) under the "id" column gets assign to 'theID'.
private void InitCountry()
{
BasicData basicData = new DAL.BasicData();
DataTable CountryListDT = basicData.GetCountryList();
txtCountry.SelectedIndex = 0;
txtCountry.ItemsSource = CountryListDT.DefaultView;
}
private void txtCountry_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
BasicData basicData = new DAL.BasicData();
object obj = (object)e.AddedItems;
Int32 CountId = (Int32)txtCountry.SelectedValue;
InitProvince(CountId);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With