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.
請任何一個建議的任何想法克服這種錯誤。 謝謝。