0
votes

Suppose I have a DataGrid and a Button. CanUserAddRows is set to True. Let this dataGrid have two DataGridTextColumns namely "Name" and "Age".

Now if user takes the following actions :

  1. He adds name as XYZ and Age as 20. Then he press enter. So a new row will be added to the datagrid.
  2. He adds name as ABC and Age as 12. Then he press enter. So a new row will be added to the datagrid.
  3. He keeps name empty and press Enter or TAB then I want to move focus to Button instead of next cell of datagrid.

I have watched many questions but I don't get the logic of if user left the name empty and how do I move focus to Button instead of next cell.

2
you can use button.Focus();Mitulát báti
But in which event? What should be the Condition?Vishal
This is fairly complex if I understand it correctly. You'll need to terminate the DataGrid's add transaction based upon inspection of the bound property, "Name".Gayot Fow
Are you using MVVM or code-behind? This will help if somebody wants to include code in their answer.Gayot Fow
BTW, the question is more about how to interact with DataGridView than moving the focus (this one being trivial).Kilazur

2 Answers

2
votes

Use DataGridView.SelectedCells[0] so you can retrieve the value of the selected cell (assuming you can only select one).

To get the actual string inside, you will have to cast the content to a proper WPF object, like TextBlock. myCell.Column.GetCellContent(cell.Item) as TextBlock

Then in a PreviewKeyDown event handler (KeyDown having known issues in DataGridView), you can use button.Focus(). (more about those issues)

//...
myDataGrid1.PreviewKeyDown += myDataGrid1_KeyDown;
//...
void myDataGrid1_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (e.Key == System.Windows.Input.Key.Enter)
    {
        var cell = myDataGrid1.SelectedCells[0];
        TextBlock cellContent = cell.Column.GetCellContent(cell.Item) as TextBlock;
        if (cellContent != null)
        {
            if (String.IsNullOrWhitespace(cellContent.Text))
                button.Focus();
        }
    }
}

About getting the column's name, it's another question, for which you can find answer here for example.

As a side note, you're not really supposed to interact directly with a DataGridView cells' values, since it's meant to be bound with a data source from which you should retrieve the data you want to test. However, you can search a bit for helper methods that can help you get what you want.

0
votes

You can define a handler for the DataGrid.KeyDown event, as:

void myDataGrid1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (e.Key == System.Windows.Input.Key.Enter)
    {
        button.Focus();
    }
}