14

I am using WPF toolkit provided DataGrid control to display product list along with its OpenStock, Description etc. In this DataGrid i have set OpenStock column to editable and rest are non-editable. What i want now when my this windows loads, I want to set keyboard focus to first cell of OpenStock column and if possible in edit mode. I searched this for 2 days and finally posting here.

any help or code sample would be helpful.

<my:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}" Margin="2,2,2,55" 
x:Name="dataGrid1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Background="White"    
AlternatingRowBackground="AliceBlue" AlternationCount="2" SelectionMode="Single" 
SelectionUnit="Cell" BorderThickness="0" IsTabStop="True">
        <my:DataGrid.Resources>
            <Style x:Key="errorStyle" TargetType="{x:Type TextBox}">
                <Setter Property="Padding" Value="-2"/>
                <Style.Triggers>
                    <Trigger Property="Validation.HasError" Value="True">
                        <Setter Property="Background" Value="Yellow"/>
                        <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},
                                Path=(Validation.Errors)[0].ErrorContent}"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </my:DataGrid.Resources>
        <my:DataGrid.Columns>
            <my:DataGridTextColumn Width="60" FocusManager.IsFocusScope="False" Binding="{Binding Path=pCode}" Header="Code" IsReadOnly="True" />
            <my:DataGridTextColumn Width="150" Binding="{Binding pName}" Header="Description"  IsReadOnly="True" />
            <my:DataGridTextColumn Width="120" Binding="{Binding CloseStock}" Header="Closing Stock"  IsReadOnly="True" />
            <my:DataGridTextColumn  Width="100" Binding="{Binding OpenStock, ValidatesOnExceptions=True}" Header="Open Stock"
                                   EditingElementStyle="{StaticResource errorStyle}"/>
            <my:DataGridTextColumn Width="150" Binding="{Binding YrlyOpenStock}" Header="Yearly Opening"  IsReadOnly="True" />

        </my:DataGrid.Columns>
    </my:DataGrid>       

thanks alot........

5 Answers 5

46

You need to set the current cell to the one you want edited and then call BeginEdit in your Loaded handler:

dataGrid1.CurrentCell = new DataGridCellInfo(
    dataGrid1.Items[0], dataGrid1.Columns[3]);
dataGrid1.BeginEdit();

If you give your DataGridTextColumn a name in XAML you can use that name rather than Columns[3].

2
  • 4
    Great answer. I had to set the focus on the dataGrid "dataGrid1.Focus();" first but then it worked.
    – jbe
    Dec 29, 2010 at 19:03
  • 1
    Note that the order of columns in the dataGrid1.Columns collection is not necessarily the order displayed on screen, see the note in msdn.microsoft.com/en-us/library/…. If you do need to index by the display order, simply store dataGrid1.Columns.OrderBy(c => c.DisplayIndex).ToArray() in a local variable, and index into that array instead.
    – Gooseberry
    Mar 5, 2016 at 10:53
8

Use this code to move the scroll view to a specific cell:

dgv.ScrollIntoView(dgv.Items[row], dgv.Columns[col]);
1

I have datagrid with TextBox in DataTemplate of DataGridTemplateColumn. Also i am using Enter instead of Tab to focus TextBox

private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        e.Handled = true;
        var TabKey = new KeyEventArgs(e.KeyboardDevice, e.InputSource, e.Timestamp, Key.Tab);
        TabKey.RoutedEvent = Keyboard.KeyDownEvent;
        InputManager.Current.ProcessInput(TabKey);
    }
}

I solve focus problem with combination of this code:

dataGrid.Focus();
//In case of more columns
//dataGrid.CurrentCell = new DataGridCellInfo(dataGrid.Items[0], dataGrid.Columns[1]);
dataGrid.BeginEdit();
(Keyboard.FocusedElement as UIElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
0

Use below function, it will work.

private void SetFocusOnGrid(DataGrid grid, int index)
{
    grid.ScrollIntoView(grid.Items.GetItemAt(index));
    grid.SelectionMode = DataGridSelectionMode.Single;
    grid.SelectionUnit = DataGridSelectionUnit.FullRow;
    grid.SelectedIndex = index;

    DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
    row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}  
0

This worked for me:

DataGridCellInfo dataGridCellInfo = new DataGridCellInfo(dataGrid1.Items[sampleRowIndex], dataGrid1.Columns[sampleColumnIndex]);
dataGrid1.SelectedCells.Clear();
dataGrid1.SelectedCells.Add(dataGridCellInfo);

This will select the cell you want to put the focus on.

A DataGridCellInfo object provides information about a cell and the data item that is associated with the cell. It is used instead of a reference to the actual DataGridCell object when the DataGrid control gets a cell, for example in the CurrentCell or SelectedCells properties. Check here for more info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.