Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable a WinForm button in time to receive focus by tabbing

Visual Studio 2010, C#

I have a ComboBox with a DropDown, AutoComplete set to SuggestAppend and the AutoCompleteSource is from the ListItems. The user keys data into it until the have the correct entry. Utill the data matches one of the list items, a button next to the combobox is disabled.

If the user hits the tab key the autocomplete feature accepts current suggestion. It also moves on to the next control in tab sequence that is enabled. Of course since I want it to go to the disbabled button I need to enable it as soon as I validate the entry.

The problem is that none of the events I've tried, PreviewKeyDown, LostFocus, SelectedIndexChanged allow me to enable the button in time for it to be proccessed and receive the focus. It always goes to the next button in tab order which is always enabled.

I am about ready to leave the button enabled and have it give an error if pressed too soon but I don't want to do it that way. I also don't want to get into have special mode flags to keep track of when these controls receive focus. Validation seems to be a normal thing, but I'm stuck.

If the SelectedIndexChanged worked when the user made a match this would be easy. It doesn't fire when the box clears nor when a typed match is found.

like image 660
Rich Shealer Avatar asked Nov 14 '22 00:11

Rich Shealer


1 Answers

You could create your own ComboBox class to encapsulate this behavior. Something like this:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            this.myComboBox1.TheButton = this.button1;

            this.myComboBox1.Items.AddRange( new string[] {
                "Monday",
                "Tuesday",
                "Wednesday",
                "Thursday",
                "Friday",
                "Saturday",
                "Sunday"
            } );

            button1.Enabled = false;
        }
    }

    public class MyComboBox : ComboBox
    {
        public Control TheButton { get; set; }

        public MyComboBox()
        {
        }

        bool IsValidItemSelected
        {
            get { return null != this.SelectedItem; }
        }

        protected override void OnValidated( EventArgs e )
        {
            if ( null != TheButton )
            {
                TheButton.Enabled = this.IsValidItemSelected;
                TheButton.Focus();
            }

            base.OnValidated( e );
        }

        protected override void OnTextChanged( EventArgs e )
        {
            if ( null != TheButton )
            {
                TheButton.Enabled = this.IsValidItemSelected;
            }

            base.OnTextChanged( e );
        }
    }
}
like image 183
ahazzah Avatar answered Dec 26 '22 08:12

ahazzah