abc cba
abc cba

Reputation: 2633

WPF - How can I get newly inserted row data row grid

By default my grid is empty, I am trying to get the row data that user insert to my grid , somehow after commit change, I have to idea how to get , I try use grid.SelectedItem , but the it always return null ,

My XAML code as below

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

My Cs Code for committing edit is as below

 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"]);
      }
 }

Code for generate table

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

What I need is when user enter 1 for No column , Apple for Description , 200 for total , I wish to get the entire row data.

Upvotes: 1

Views: 1494

Answers (1)

Arindam Nayak
Arindam Nayak

Reputation: 7462

You can access newly inserted row to datagrid using following.

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"]);
      }
 }

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

Upvotes: 1

Related Questions