首页 > 解决方案 > 从 DataGrid WPF 获取数据

问题描述

当 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。

标签: c#wpfvisual-studio

解决方案


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

如果您从数据库中检索的对象覆盖.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";
    }
}

推荐阅读