Click here to Skip to main content
15,887,888 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi there,

I am stuck in a small thing.I am doing my work in winApp.I want to set the focus on dropdownlist(dropdownstyle Property of a combobox)while pressing enter from a textbox.so simply while I moved from a textbox my focus should go to the combobox.

so please some body help me out.

Thanks,
Posted
Comments
[no name] 7-Feb-13 6:03am    
your code ?

C#
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
        this.comboBox1.Focus();
}

will get you to the combobox. I would advise that the TabIndex property of the comboBox is also set to the the TabIndex of the text box plus 1
 
Share this answer
 
You can try more generic approach, which handles this specific behaviour on all TextBoxes.
Simply put this code into App.xaml.cs code behind:
C#
/// <summary>
/// Handles the Startup event of the Application control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.StartupEventArgs"/> instance containing the event data.</param>
private void Application_Startup(object sender, StartupEventArgs e)
{
    // Attach to global PreviewKeyDown Event
    EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewKeyDownEvent, new RoutedEventHandler(TextBox_PreviewKeyDown));
}

/// <summary>
/// Handles the PreviewKeyDown event of the TextBox control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private static void TextBox_PreviewKeyDown(object sender, RoutedEventArgs e)
{
    if ((e as KeyEventArgs).Key == Key.Enter) // Enter pressed
    {
        if ((e.Source as TextBox).AcceptsReturn) // Ignore when TextBox accepts enter key
            return;

        // Get currently focused element
        var focusedElem = Keyboard.FocusedElement as UIElement;

        if (focusedElem != null)
        {
            // Focus next element
            focusedElem.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

            // Check if next element is ComboBox
            var comboBox = Keyboard.FocusedElement as ComboBox;

            // Open DropDown
            if (comboBox != null)
                comboBox.IsDropDownOpen = true;
        }

        e.Handled = true;
    }
}

Also my example contains code for auto opening combo box drop down.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900