Search code examples
c#wpfxamldatagridedit

Text of a cell is highlighted after starting editing


I load the contents of a database (mdb) into a DataTable object and display them in a DataGrid so that I can edit them. As soon as I start editing a cell (pressing F2), the entire text is selected.

Left (actual): All text is selected on edit. Right (expected): Caret is moved to end on edit.

Is there a way to prevent this marking?

My DataGrid markup:

<DataGrid VirtualizingStackPanel.VirtualizationMode="Standard" Height="750" Width="1920" CanUserResizeColumns="True" CanUserReorderColumns="False" CanUserResizeRows="False" RowHeight="25" FrozenColumnCount="1" x:Name="DataGrid1" CanUserAddRows="False" CanUserSortColumns="False" AutoGenerateColumns="False" FontSize="13" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,120" SelectionUnit="CellOrRowHeader" SelectionMode="Extended">

   <DataGrid.Columns>
       <DataGridTextColumn Width="450" Header=" Column1 " Binding="{Binding Column1}">
           <DataGridTextColumn.EditingElementStyle>
               <Style TargetType="TextBox">
                   <Setter Property="MaxLength" Value="150"></Setter>
               </Style>
           </DataGridTextColumn.EditingElementStyle>
       </DataGridTextColumn>
   
       <DataGridTextColumn Width="120" Header=" Column2 " Binding="{Binding Column2}">
           <DataGridTextColumn.EditingElementStyle>
               <Style TargetType="TextBox">
                   <Setter Property="MaxLength" Value="10"></Setter>
               </Style>
           </DataGridTextColumn.EditingElementStyle>
       </DataGridTextColumn>
   </DataGrid.Columns>
   
   <DataGrid.RowStyle>
       <Style TargetType="DataGridRow">
           <EventSetter Event="KeyDown"  Handler="DATAGRID_Keydown" ></EventSetter>
       </Style>
   </DataGrid.RowStyle>

</DataGrid>

My C# Code:

private void DATAGRID_Keydown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Tab | e.Key == Key.F2)
    {
      DataGrid1.BeginEdit();
    }
}

Solution

  • you can use the PreparingCellForEdit event for the DataGrid:

    XAML

    <DataGrid ... PreparingCellForEdit="DataGrid_PreparingCellForEdit">
    

    C# (It will place the cursor at the end of the current cell text)

    private void DataGrid_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
    {
        ((TextBox)e.EditingElement).SelectionStart = ((TextBox)e.EditingElement).Text.Length;
    }
    

    You can use use ((TextBox)e.EditingElement).SelectionStart = 0; to place the cursor at the beginning of the original text of that cell.