Search code examples
c#.netcomboboxtextboxfocus

Setting Focus on next item becoming visible while leaving ComboBox


I have a ComboBox with AutoCompleteMode set to Suggest. The next control in sequence is a TextBox. Depending on the selected item of the ComboBox the TextBox is visible or not visible. Furthermore there another text shouldn't be entered which isn't contained in the elements of the list of the ComboBox. So at leaving of the ComboBox I Check the value at Validating.

private void cb_Validating(object sender, CancelEventArgs e)
{
  if(cb.SelectedValue == null)
  {
    e.Cancel = true;
  }
  tb.Visible = cb.Text.Contains("XX"); // makes TextBox visible/invisible
}

Now there is the problem if the TextBox is invisible and a user types in the ComboBox some letters and goes with key down to an item which makes the TextBox visible and press the tabulator key then the focus skips the following text box which becomes visible. How to achive that the text box will not be skipped in this case?


Solution

  • Implement the Validated event to show and select the TextBox if the condition is met. Otherwise, hide it and call the SelectNextControl method to select the next control in the tab order.

    private void cb_Validating(object sender, CancelEventArgs e)
    {
        e.Cancel = cb.SelectedItem == null;            
    }
    
    private void cb_Validated(object sender, EventArgs e)
    {
        tb.Visible = cb.Text.Contains("some text");
        if (tb.Visible) tb.Select();
        else SelectNextControl(cb, true, true, true, true);
    }