How to reset the newly added row automatically in DataGrid, when DataGrid binds with DataTable?

Elad770

New member
Joined
Oct 4, 2021
Messages
2
Programming Experience
1-3
hello
The datagrid does binidng with a DataTable that holds within it a db table with required fields. The problem is that when I try to get out of focus in the new row from any cell from the same row without really filling the same cell, the datagrid does not allow me to access other rows that are already filled with content and requires me to fill the last row.
I use with cellEditing event because I want to update a specific cell in the table on the other hand I want to add a new row to the table.
I tried disabling this row by CancelEdit and then running BeginEdit but it does not take it out of normal focus. And still obliges me to complete the row.

C#:
<!--file xaml-->
<Grid Background="#2e3137" Grid.Row="0" Grid.ColumnSpan="2">
            <TextBox  Margin="0,0,20,0" Style="{StaticResource resTextBox}" />
        </Grid>
        <Grid Name="SecondGrid" Margin="0,20,20,0" Grid.Row="1"  Grid.Column="1">
            <DataGrid  Name="Dg"  SelectionUnit="FullRow"  VerticalAlignment="Top"  VerticalScrollBarVisibility="Auto" FlowDirection="RightToLeft" HorizontalContentAlignment="Center" HorizontalAlignment="Right" FontSize="18" HorizontalScrollBarVisibility="Auto" Foreground="{Binding ElementName=GridMain, Path=Background}" Background="#FFE3E3E3" RowStyle="{StaticResource RowStyleWithAlternation}"
                      AutoGenerateColumns="False" CellEditEnding="Dg_CellEditEnding" />
        </Grid>
    </Grid>
//in code behind
 private void FillDataGrid()
        {
            //schemaTable is dataTable of schema of table of db 
            foreach (DataRow dr in pro.schemaTable.Rows)
            {
                DataGridTextColumn title = new DataGridTextColumn();
                title.Header = dr[0];
                title.Binding = new Binding(title.Header.ToString())
                { Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
          
                if (bool.Parse(dr["IsAutoIncrement"].ToString()))
                {
                    title.Visibility = Visibility.Hidden;
                    string uniqe = dr[0].ToString();
                    pro.currentTable.Columns[uniqe].DefaultValue = 0;
                }
                Dg.Columns.Add(title);
            }

            Dg.ItemsSource = pro.currentTable.DefaultView;
        }

private void Dg_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            DataRowView row_current = (e.Row.Item as DataRowView);
            row_current.Row.CancelEdit();
            row_current.Row.BeginEdit();
           
            if (row_current.Row[pro.ColUniqe].ToString() == "0")
            { 
              //.........
            }
            else
            {
               //....
             }
        }
How can this be done without adding more settings in XAML?
 

Elad770

New member
Joined
Oct 4, 2021
Messages
2
Programming Experience
1-3
hello
I work with DataGrid in WPF.
The datagrid does binidng with a DataTable that holds within it a db table with required fields. The problem is that when I try to get out of focus in the new row from any cell from the same row without really filling the same cell, the datagrid does not allow me to access other rows that are already filled with content and requires me to fill the last row. the whole row itself is empty!
I tried disabling this row by CancelEdit and then running BeginEdit but it does not take it out of normal focus. And still obliges me to complete the row
C#:
<!--file xaml-->

<Grid Background="#2e3137" Grid.Row="0" Grid.ColumnSpan="2">

            <TextBox  Margin="0,0,20,0" Style="{StaticResource resTextBox}" />

        </Grid>

        <Grid Name="SecondGrid" Margin="0,20,20,0" Grid.Row="1"  Grid.Column="1">

            <DataGrid  Name="Dg"  SelectionUnit="FullRow"  VerticalAlignment="Top"  VerticalScrollBarVisibility="Auto" FlowDirection="RightToLeft" HorizontalContentAlignment="Center" HorizontalAlignment="Right" FontSize="18" HorizontalScrollBarVisibility="Auto" Foreground="{Binding ElementName=GridMain, Path=Background}" Background="#FFE3E3E3" RowStyle="{StaticResource RowStyleWithAlternation}"

                      AutoGenerateColumns="False" CellEditEnding="Dg_CellEditEnding" />

        </Grid>

    </Grid>

//in code behind

 private void FillDataGrid()
        {
            //schemaTable is dataTable of schema of table of db 

            foreach (DataRow dr in pro.schemaTable.Rows)
            {
                DataGridTextColumn title = new DataGridTextColumn();
                title.Header = dr[0];
                title.Binding = new Binding(title.Header.ToString())
                { Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
          
                if (bool.Parse(dr["IsAutoIncrement"].ToString()))
                {
                    title.Visibility = Visibility.Hidden;
                    string uniqe = dr[0].ToString();
                    pro.currentTable.Columns[uniqe].DefaultValue = 0;
                }
                Dg.Columns.Add(title);
            }

            Dg.ItemsSource = pro.currentTable.DefaultView;
        }


private void Dg_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            DataRowView row_current = (e.Row.Item as DataRowView);
            row_current.Row.CancelEdit();
            row_current.Row.BeginEdit();
           
            if (row_current.Row[pro.ColUniqe].ToString() == "0")
            { 
              //.........

            }

            else

            {

               //....

             }

        }

How can this be solved simply without configuring additional settings in XAML?
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
4,029
Location
Chesapeake, VA
Programming Experience
10+
First of all, why are you using WPF as if it were WinForms? In WPF, in general you would only be handling events directly to do a UI type operations, not business logic type operations. Business logic operations should live in the View Model, if you are correctly using WPF with the MVVM pattern.

Anyway, according to the documentation, all that [il]CancelEdit()[/il] does is it that it cancels the current editing procedure on the row which I take to mean that it changes an internal flag that keeps track of row versions and modification state. It says nothing about changing the focus which seems to be what you were expecting to happen. Perhaps try changing the current selected cell as well?

Also WPF is very highly driven by events within its internal message dispatch queue. Events need to be driven by the dispatcher. So unlike WinForms which is Windows message driven (despite the WinForms documentation calling the Windows message events) where you can do a [il]SendMessage()[/il] from within another Windows message handler, in WPF you may need to let the dispatcher have a go at things, which will require you to make your code state driven.
 
Top Bottom