【发布时间】:2021-01-24 01:58:45
【问题描述】:
我的最终目标是使用运行时从数据库中检索到的数据填充 DataGrid。我的方法是首先从该数据库中提取所有列,然后为每一行的每一列提取相应的数据,如下所示:
ReadOnlyCollection<Field> tablefields = {//has the fields populated from the database};
//adding all the columns to the data table
var datatable = new DataTable("mytable");
foreach (var field in tablefields)
{ datatable.Columns.Add(field.Name, wFieldType); }
//Then add the rows
while (cursor.MoveNext())
{
var tableRow = datatable.NewRow();
var row = cursor.Current;
for(var i = 0; i < tablefields.Count; i++)//add the values for each field to the data table.
{
tableRow[i] = row[i] ?? DBNull.Value;
}
datatable.Rows.Add(tableRow);
}
但是,我的问题是,我要提取的某些列必须采用 DataGridComboBoxColumn 的形式,因为它们在数据库的下拉列表中具有预设值。最好的情况是,当我将列一一拉到我的数据表中时,我会检测那些具有预设值的列,并在将它们添加到数据表之前将它们设为 DataGridComboBoxColumn 类型。我显然不能这样做,因为你不能在 dataTable 上有一个组合框。我的下一个选项是使用 dataGrid 在运行时从数据库中加载列和数据。 我可以使用组合框添加列,如下面的代码所示,但我无法弄清楚如何将我的数据从数据库中获取到包含预加载列的 dataGrid 中。
DataGridComboBoxColumn cb = new DataGridComboBoxColumn();
cb.ItemsSource = new List(){to be populated later}
cb.Header = field.Name;
MyDataGrid.Columns.Add(cb);
上面的代码用作测试 DataGridComboBoxColumn 的示例,果然我能够看到带有组合框的数据网格。我只是不知道如何将我的数据库数据放入表中。我会很感激任何想法。 PS:由于我正在使用的api,我无法使用datagridview,所以我仅限于datagrid。
【问题讨论】:
标签: c# wpf datagrid datagridcomboboxcolumn