2016-09-29 33 views
0

アプリケーションのメインウィンドウにはデータグリッドがあり、データベースからデータが読み込まれます。 (データテーブルからデータグリッドをバインド)。Datagrid行(WPF)を削除する

データグリッドは、3カラム・ウィンドウローディング、データグリッドの時間データテーブルとpoulated

<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. 

を投げてきた削除してくださいクリックしたとき。 ありがとうございます。代わりにやっての

答えて

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; 
      } 
     } 
この方法を試すことができます
関連する問題