将组合框绑定到代码隐藏中的数据集(无 XAML)

本文关键字:数据集 XAML 隐藏 组合 绑定 代码 | 更新日期: 2023-09-27 17:56:26

如何在代码隐藏中将组合框绑定到数据集,而无需使用 XAML:

我尝试了以下内容,但我的所有组合框项目都是"System.Data.DataRowView"而不是实际值。怎么了?

string str = @"SELECT * FROM FooTable";
da.SelectCommand = new SqlCeCommand(str, connection);
da.Fill(devDs, "FooTable");
dt = ds.Tables["FooTable"];
comboBox1.ItemsSource = devDt.DefaultView;

将组合框绑定到代码隐藏中的数据集(无 XAML)

您必须设置DisplayMemberPath属性

combobox.DisplayMemberPath = "ColumnName"
可以使用

comboBox1.DisplayMemberPath来设置表中的哪一列应用于 UI 演示。

测试样品:

var dataTable = new DataTable();
dataTable.Columns.Add("Id", typeof(int));
dataTable.Columns.Add("Name", typeof(string));
dataTable.Rows.Add(1, "Test1");
dataTable.Rows.Add(2, "Test2");
comboBox1.ItemsSource = dataTable.DefaultView;
comboBox1.DisplayMemberPath = "Name";