有没有办法从 DataTable 填充 DataGrid 中的 DataGridComboBoxColumn?
Is there a way to populate a DataGridComboBoxColumn in a DataGrid from a DataTable?
我想我问的问题与 类似,但我的问题来自 DataTable 而不是 class。我创建了一个数据集作为示例。但基本上,当我加载它时该列是空白的,但是当我从组合框中 select 一个项目时,它仍然按预期编辑数据表,但我想我缺少将数据绑定到该列的东西.
DataTable dt;
public MainWindow()
{
InitializeComponent();
CreateDT();
}
public void CreateDT()
{
dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Position", typeof(string));
// List for the options in the comboBox
List<string> list = new List<string>()
{
"Position 1",
"Position 2",
"Position 3",
"Position 4",
"Position 5"
};
// datatable
for (int i = 0; i < 10; i++)
{
dt.Rows.Add("Person A", "Position A");
}
ComboBoxColumn.ItemsSource = list;
RestoreTable.ItemsSource = dt.DefaultView;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Adding a break point here so I can debug what the datatable looks like after selecting a value
}
有了XAML就可以了
<Grid>
<DataGrid Name="RestoreTable" AutoGenerateColumns="False" HorizontalAlignment="Center" VerticalAlignment="Top" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridComboBoxColumn x:Name="ComboBoxColumn"
Header="Position"
SelectedItemBinding="{Binding List}"
SelectedValueBinding="{Binding Position}"
???????/>
</DataGrid.Columns>
</DataGrid>
<Button Content="Button" HorizontalAlignment="Left" Margin="703,352,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
问题是因为 DataTable 中的值不在 DataGridComboBoxColumn 列表中,所以它没有显示,将 "Position A" 添加到列表或将 "Position A" 更改为 "Position 1" 解决了这个问题。
我想我问的问题与
DataTable dt;
public MainWindow()
{
InitializeComponent();
CreateDT();
}
public void CreateDT()
{
dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Position", typeof(string));
// List for the options in the comboBox
List<string> list = new List<string>()
{
"Position 1",
"Position 2",
"Position 3",
"Position 4",
"Position 5"
};
// datatable
for (int i = 0; i < 10; i++)
{
dt.Rows.Add("Person A", "Position A");
}
ComboBoxColumn.ItemsSource = list;
RestoreTable.ItemsSource = dt.DefaultView;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Adding a break point here so I can debug what the datatable looks like after selecting a value
}
有了XAML就可以了
<Grid>
<DataGrid Name="RestoreTable" AutoGenerateColumns="False" HorizontalAlignment="Center" VerticalAlignment="Top" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridComboBoxColumn x:Name="ComboBoxColumn"
Header="Position"
SelectedItemBinding="{Binding List}"
SelectedValueBinding="{Binding Position}"
???????/>
</DataGrid.Columns>
</DataGrid>
<Button Content="Button" HorizontalAlignment="Left" Margin="703,352,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
问题是因为 DataTable 中的值不在 DataGridComboBoxColumn 列表中,所以它没有显示,将 "Position A" 添加到列表或将 "Position A" 更改为 "Position 1" 解决了这个问题。