将下拉列表添加到DataGrid列并在运行时C#填充行

时间:2020-10-09 00:29:02

标签: c# wpf datagrid datagridcomboboxcolumn

我的最终目标是在运行时从数据库中检索数据来填充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的形式,因为它们在数据库的下拉列表中具有预设值。最好的情况是,当我将列逐一拉入dataTable时,我将检测到具有预设值的列并将其类型设置为DataGridComboBoxColumn,然后再将其添加到dataTable中。我显然不能这样做,因为您不能在dataTable上有一个组合框。我的下一个选择是使用dataGrid在运行时从数据库加载列和数据。 我能够使用下面的代码所示的组合框添加列,但是我无法弄清楚如何将数据库中的数据放入包含预加载列的dataGrid中。

DataGridComboBoxColumn cb = new DataGridComboBoxColumn();
cb.ItemsSource = new List(){to be populated later}
cb.Header = field.Name;                  
MyDataGrid.Columns.Add(cb);

上面的代码用作测试DataGridComboBoxColumn的示例,并确保我能够看到带有组合框的datagrid。我只是不知道如何将我的数据库数据放入表中。我将不胜感激。 PS:由于使用的api,我无法使用datagridview,因此我仅限于datagrid。

1 个答案:

答案 0 :(得分:1)

您应将SelectedItemBinding设置为对DataTable中包含要选择的ItemsSource中的值的列的绑定:

cb.SelectedItemBinding = new Binding("AColumnInYourDataTable");

如果您将ItemsSource设置为List<T>是复杂类型的T,则应该设置SelectedValueBindingSelectedValuePath和{{1 }}属性:

DisplayMemberPath