删除Datagrid行(WPF)
问题描述:
主窗口应用程序具有数据网格,该数据网格从数据库填充。 (从数据表中绑定数据网格)。删除Datagrid行(WPF)
数据网格具有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>
当与数据表poulated窗口加载,数据网格的时间。
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.
请任何一个建议的任何想法克服这种错误。 谢谢。
答
而不是做的:
grd.Items.RemoveAt(grd.SelectedIndex);
你应该从底层源移除。
尝试从数据表中删除它,它将从视图中消失。采用MVVM方法可以让您更轻松,因为您永远不需要触摸UI。
答
要删除从电网的项目,你可以试试这个方法
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
object item = grd.SelectedItem;
string CourseName = (grd.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
MessageBoxResult result = System.Windows.MessageBox.Show("Are you sure you want to delete the course " + CourseName + "?");
if (result == MessageBoxResult.OK)
{
var itemSource = grd.ItemsSource as DataView;
itemSource.Delete(grd.SelectedIndex);
grd.ItemsSource = itemSource;
}
}