从DataGrid WPF获取数据

时间:2019-02-15 05:58:08

标签: c# wpf visual-studio

当ComboBox的文本与DataGrid的记录相等时,如何从 DataGrid 获取数据:

combobox1.ItemsSource = database.Mahs.ToList();

combobox1.DisplayMemberPath = "MahName";

private void datagrid_customer_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var data = datagrid_customer.SelectedItem;
    string id = (datagrid_customer.SelectedCells[0].Column.GetCellContent(data) as TextBlock).Text;
    txt_f1.Text = id;
}

它显示了我的ID,但是当我选择了项目但我想在combobox.Text = DataGrid中行的名称时显示我的ID,然后显示了该行的ID。

1 个答案:

答案 0 :(得分:0)

我建议您稍微改变一下方法,并从两个控件中检索整个对象以进行比较。这样,您就可以完全访问每个选定对象的属性。

如果您要从数据库中检索的对象覆盖.Equals.GetHashCode,则可以取消下面的某些if语句。但是,为了让您入门,这里是您的变更侦听器的快速示例

private void datagrid_customer_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // Cast the objects from your DataGrid and your ComboBox. 
    YourDataObject dataItem = (YourDataObject)dataGrid1.SelectedItem;
    YourDataObject comboItem = (YourDataObject)combo.SelectedItem;

    // Compare your objects and decide if they're the same. Ideally you would 
    // have Equals and HashCode overridden so you could improve this
    if (dataItem == null || comboItem == null)
        text.Text = "Not Matching";
    else
    {
        if (dataItem.MahName == comboItem.MahName)
            // You've got full access to the object and all it's properties
            text.Text = dataItem.Id.ToString();
        else
            text.Text = "Not Matching";
    }
}