Share via


What is Control.SelectNextControl(...)?

Today I recieved a question on Winforms discussion list about SelectNextControl function on control and I thought it might be worth sharing some thoughts on this topic. The name "SelectNextControl" suggests that this function would select the next control in the taborder starting from the control on which this function is called. But THAT’S NOT THE CASE.

Infact, this function tries to select the next "child" control (in the taborder) of the control on which this function is called. Let me explain with a scenario to make this point easy to understand. Say you have a form which has couple of textBoxes and a button. In the button click you want to change the focus to the next control in tarorder from the Button. (which is the ActiveControl on the Form when you click it) 

The Following code is WRONG:

private void button1_Click(object sender, System.EventArgs e)

{

         ((Button)sender) .SelectNextControl(ActiveControl, true, true, true, true);

}

 

The above code would try to select the next control within Button and since there is NO child control within button this will just be a NO-OP.

What you really want is to do the following:

 

private void button1_Click(object sender, System.EventArgs e)

{

         Control parent = ((Button)sender).Parent;

         parent.SelectNextControl(ActiveControl, true, true, true, true);

}

So be careful about using this function as the MSDN help doesnt explicity mention this behavior.

Comments

  • Anonymous
    February 26, 2005
    Doesn't that assume that the parent of the button is the form? What if the button is currently on a user control or panel? Should you be using TopLevelControl istead? I'm asking because I don't really know the answer.
  • Anonymous
    February 26, 2005
    Maybe it should be redesigned if you have to explain it that much.
  • Anonymous
    February 27, 2005
    Matt: The code (in button click) doesnt assume that the button is on the form.I am casting the Parent of the button to a control and hence this code would work if the button is on a panel or userControl since the SelectNextControl would get called on the panel or userControl in such a case. But if you want to by-pass the parent-hiearchy and focus the control on the main (TOPLEVEL) then you can call the TopLevelControl.

    -SOak.
  • Anonymous
    January 29, 2007
    The question of using a hardware button to tab through the controls on a form came up on the Compact