删除数据网格行 (WPF)

2023-12-21

应用程序的主窗口有数据网格,它是从数据库填充的。 (从数据表绑定数据网格)。

数据网格有 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>

当窗口加载时,数据网格填充数据表。

    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.

请任何人提出任何克服此错误的想法。 谢谢。


你想从网格中删除项目,你可以尝试这个方法

 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;
            }
        }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

删除数据网格行 (WPF) 的相关文章

随机推荐