Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

C# WPF Select in DataGrid the first row with pressing Enter from a Textbox

I have a TextBox (SearchBox - TabIndex=0) and a populated DataGrid TabIndex=1. I want after input of the keyword in the SearchBox by pressing Enter to select the first row in the DataGrid.

So far i have just this:

  private void txtSearchBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (e.Key == System.Windows.Input.Key.Enter)
        {
            System.Windows.Controls.TextBox txtb = sender as System.Windows.Controls.TextBox;
            txtb.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }

It selects the whole DataGrid and not the row.

Thank you for your help.

EDIT: I′ve added this to code above and the problem was solved :-)

dataGrid.SelectedItem = dataGrid.Items[0];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I′ve added the following code to the Searchbox_KeyDown

dataGrid.SelectedItem = dataGrid.Items[0];

And this solved my problem!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...