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.