开发者

how to bind ComboBox with DataTable

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 wh开发者_StackOverflow中文版en 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.


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);
    }


My XAML:

 <ComboBox  Margin="10,0,0,0" x:Name="listStatus" 
HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="200" SelectionChanged="listStatus_SelectionChanged" 
    DisplayMemberPath="Status" SelectedValuePath="StatusID" />

The Code Behind:

private void Bind_StatusList()
{
  Service1 serv = new Service1();
  dtStatus = serv.GetStatuses(); // a WCF service getting the DataTable from a view from the database.
  listStatus.ItemsSource = dtStatus.DefaultView;
}

This doesn't give a selected option when the window starts, but at least the list of Status is showing when I click the comboBox.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜