c# - 从 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。
解决方案
我建议稍微改变您的方法,并从两个控件中检索整个对象以进行比较。这样您就可以完全访问每个选定对象的属性。
如果您从数据库中检索的对象覆盖.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";
}
}
推荐阅读
- c++ - 为 macOS-x86_64 构建,但尝试链接为 macOS-arm64 构建的文件
- ios - SwiftUI:如何让用户通过选项“light”、“dark”和“system”实时设置应用程序外观?
- vb.net - 每次调用 IEnumerable 对象时都会重新运行 IEnumerable 定义,导致当只有一个项目时第一项被设置为空
- python - 导入 png 时 Python 权限错误
- python - 如何在python中为具有多个索引的数据框制作堆叠图?
- mysql - 即使有索引,MySQL-inner join 也很慢
- javascript - 如何摆脱网格上的双边框?
- mysql - 如何对所有不为NULL的字段执行sql操作?
- python - AttributeError: 'str' 对象没有属性 'decode' python 错误
- c# - Visual Studio 引用与依赖项、程序集和包