如何从列表框中检索绑定到数据表的所选项的id?

时间:2013-02-21 06:22:53

标签: c# sql-server

我有一个列表框,我绑定到Datable [employee],其中列表框显示员工姓名。

如何从数据库中获取所选项目id,如employee_id

如果代码

,这是我的部分

XAML -

ListBox ItemsSource="{Binding}" DisplayMemberPath="employee_name" HorizontalAlignment="Left" Margin="16.362,108.171,0,44.541" Name="lstbxEmloyee" Width="333.603" SelectionChanged="lstbxEmployee_SelectionChanged" 

的.cs

EmployeeData _employeeData = new EmployeeData();

_employeeData.GetEmployeeName();

lstbxEmloyee.ItemsSource = _employeeData._dataTable.DefaultView;

我想从列表框

中为选定的employee_id提取employee_name

请帮帮我

并感谢你....

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
         // you can bind your data as per your requirement
        lstbxEmloyee.ItemsSource = GetTable().DefaultView; 
    }

    private void lstbxEmloyee_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      DataRow dr=((DataRowView) (lstbxEmloyee.SelectedItem)).Row;
      int Emp_id = Convert.ToInt32(dr["employee_ID"]);
      MessageBox.Show(Emp_id.ToString());
    }

    DataTable GetTable()
    {
        DataTable table = new DataTable();
        table.Columns.Add("employee_ID", typeof(int));
        table.Columns.Add("employee_name", typeof(string));        

        table.Rows.Add(1,"David");
        table.Rows.Add(2,"Sam");
        table.Rows.Add(3,"Christoff");
        table.Rows.Add(4, "Janet");
        table.Rows.Add(5, "Melanie");

        return table;
    }     

答案 1 :(得分:0)

是的,我做到了。我想出了我的问题的解决方案 我在代码中进行了如下更改   的 XAML -   ListBox ItemsSource =“{Binding}”DisplayMemberPath =“employee_name” SelectedValuePath =“employee_id” Horizo​​ntalAlignment =“Left”Margin =“16.362,108.171,0,44.541”Name =“lstbxEmloyee”Width =“333.603 “SelectionChanged =”lstbxEmployee_SelectionChanged“

<强>的.cs string _selectedProject = lstbxProjects.SelectedItem.ToString();

它是“SelectedValuePath”和“SelectedValue”之间的绑定 哪里-  SelectedValuePath - 从datatable引用哪个列  SelectedValue-从

中提供值