2016-09-29 290 views
0

主窗口應用程序具有數據網格,該數據網格從數據庫填充。 (從數據表中綁定數據網格)。刪除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. 

請任何一個建議的任何想法克服這種錯誤。 謝謝。

回答

0

而不是做的:

grd.Items.RemoveAt(grd.SelectedIndex); 

你應該從底層源移除。

嘗試從數據表中刪除它,它將從視圖中消失。採用MVVM方法可以讓您更輕鬆,因爲您永遠不需要觸摸UI。

0

要刪除從電網的項目,你可以試試這個方法

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; 
      } 
     }