将CollectionView.CurrentItem转换为DataRow?

时间:2014-01-06 06:32:08

标签: c# .net wpf

我正在尝试将VB中“How Do I: Create a Simple Data Entry Form in WPF?”上的MSDN视频转换为C#。我被困在20:11。

我首先创建一个Typed DataSet和一个CollectionView:

private CustomerDataSet CustomerData = new CustomerDataSet();
private CustomerDataSetTableAdapters.CustomersTableAdapter taCust = new CustomerDataSetTableAdapters.CustomersTableAdapter();
private CustomerDataSetTableAdapters.TableAdapterManager taManager = new CustomerDataSetTableAdapters.TableAdapterManager();
private CollectionView View;

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    this.taCust.Fill(this.CustomerData.Customers);
    this.DataContext = CustomerData.Customers;

    this.View = (CollectionView)CollectionViewSource.GetDefaultView(this.CustomerData.Customers);
}

我有线导航按钮很好。当我连接删除按钮的事件时,我的麻烦就开始了。根据MSDN的CollectionView.CurrentItem documentation,我应该能够将CurrentItem转换为另一个对象。我想将CurrentItem转换为DataRow(或Typed DataRow),以便我可以调用DataRow的Delete方法。

private void btnDelete_Click(object sender, RoutedEventArgs e)
{
    if (this.View.CurrentPosition != -1)
    {
            // This doesn't work, throws null exception:
            // DataRow row = this.View.CurrentItem as DataRow;
            // 
            // This doesn't work either, throws null exception: 
            // CustomerDataSet.CustomersRow row = this.View.CurrentItem as CustomerDataSet.CustomersRow;
            MessageBox.Show("row:" + row.ToString());
     }
}

我哪里错了?谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

像这样提取行

DataRow row = (this.View.CurrentItem as DataRowView).Row;