WPF - 如何获取新插入的行数据行网格

时间:2014-11-15 16:53:38

标签: c# wpf c#-4.0

默认情况下我的网格是空的,我试图获取用户插入到我的网格的行数据,不知何故在提交更改后,我不得不知道如何获取,我尝试使用grid.SelectedItem,但它总是返回null,

我的XAML代码如下

 <DataGrid x:Name="grdInfo" Height="373" VerticalAlignment="Top" DockPanel.Dock="Top" Margin="0,10,0,0" RowEditEnding="grdInfoSave" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="No" Binding="{Binding No}" Width="50" />
                <DataGridTextColumn Header="Description" Binding="{Binding Description}" Width="*" />
                <DataGridTextColumn Header="Total" Binding="{Binding Total}" Width="120" />
            </DataGrid.Columns>
 </DataGrid>

我提交编辑的Cs代码如下

 private void grdInfoSave(object sender, DataGridRowEditEndingEventArgs e )
 {
      if (e.EditAction == DataGridEditAction.Commit)
      {
        //Try to get the user inserted value and process it
        DataRowView row = (DataRowView)grdInfo.SelectedItem;
        int No = Convert.ToInt32(row["No"]);
      }
 }

生成表的代码

 private void genTable()
 {
        DataTable dtInfo = new DataTable(); 

        dtInfo.Columns.Add(new DataColumn("No", Type.GetType("System.Int32")));
        dtInfo.Columns.Add(new DataColumn("Description", Type.GetType("System.String")));
        dtInfo.Columns.Add(new DataColumn("Total", Type.GetType("System.String")));

        grdInfo.ItemsSource = dtInfo.DefaultView;  
 }

我需要的是当用户为No列输入1时,Apple为描述输入200,为总数输入200,我希望得到整个行数据。

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容访问新插入的行到数据网格。

private void grdInfoSave(object sender, DataGridRowEditEndingEventArgs e )
 {
      if (e.EditAction == DataGridEditAction.Commit)
      {
        //Try to get the user inserted value and process it
        DataRow newrow= e.Row.DataContext as DataRow; // If datarow does not work, replace will required databind class.
        String new_desc = newrow["Description"].ToString();
        DataRowView row = (DataRowView)grdQuoteDetail.SelectedItem;
        int No = Convert.ToInt32(row["No"]);
      }
 }

来源 - http://blogs.u2u.be/diederik/post/2009/09/29/Inserting-Updating-and-Deleting-from-a-WPF-DataGrid.aspx