【发布时间】:2017-02-07 06:06:13
【问题描述】:
应用程序的主窗口具有从数据库填充的数据网格。 (从数据表中绑定数据网格)。
数据网格有 3 列-
<DataGrid.Columns>
<DataGridTextColumn Header= Id" Binding="{Binding Id}" Width="250"></DataGridTextColumn>
<DataGridTextColumn Header= Name" Binding="{Binding Name}" Width="250"></DataGridTextColumn>
<DataGridTemplateColumn Header="Action" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Name="btnEdit" Content="Edit" Width="90" Click="btnEdit_Click" />
<Button Name="btnDelete" Content="Delete" Width="90" Click="btnDelete_Click" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
当窗口加载的时候,datagrid填充了数据表。
DataTable o_DataTable = new DataTable();
o_DataTable.Columns.Add("Id", typeof(string));
o_DataTable.Columns.Add("Name", typeof(string));
o_DataTable.Rows.Add("1","A");
o_DataTable.Rows.Add("2","B");
this.grd.ItemsSource = o_DataTable.DefaultView;
点击删除按钮的代码如下:
private void Button_Click(object sender, RoutedEventArgs e)
{
object item = grd.SelectedItem;
string CourseName = (grd.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
MessageBoxResult result = MessageBox.Show("Are you sure you want to delete the course " + CourseName + "?");
if (result == MessageBoxResult.OK)
{
grd.Items.RemoveAt(grd.SelectedIndex);
}
}
当我点击删除按钮时抛出异常
An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll
Additional information: Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.
请任何人提出任何想法来克服此错误。 谢谢。
【问题讨论】:
标签: c# wpf binding datatable datagrid