Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can I select one of a textbox from 10 textbox by random function?
Posted
Updated 8-Jan-11 2:25am
Comments
Dalek Dave 8-Jan-11 8:26am    
Minor Edit for Grammar.

The obvious solution:
Generate a random number between 1 and 10 (or 0 and 9) using Random.Next[^], after that switch by generated number and call Focus[^] or Select[^] method for the chosen TextBox.

[TIP]
If you keep your TextBox references in array or list the switch statement will be replaced with a one-line indexing in that array. :)
[/TIP]
 
Share this answer
 
v4
Comments
Dalek Dave 8-Jan-11 8:26am    
Yep, that's how I would do it.
C#
private Random rnd = new Random();
        private void SelectTextBox()
        {
            int i = rnd.Next(1, 10);
            foreach (Control c in this.Controls)
            {
                if (c is TextBox && c.Name == "textBox" + i.ToString())
                {
                    c.Select();
                    break;
                }
            }
        }
 
Share this answer
 
v3
Comments
Nuri Ismail 8-Jan-11 4:42am    
Actually rnd.Next(10) will return a value in interval [0, 9] but the default names for textboxes start with number 1 (i.e. textBox1) therefore I think that "textBox" + i.ToString() is not very appropriate in this case (what if the value of i is 0?). Also, what if there are more textboxes and these that will get the random focus are not the first ones added to the form? I know that the OP was not specific and for a general question of this type I believe a general answer suits better, but that is a matter of taste. :)

Best Regards,
Nuri
jerrykid 8-Jan-11 4:44am    
Hi Nuri, thanks, I updated :)
ely z 8-Jan-11 5:09am    
thanks but where add this code
jerrykid 8-Jan-11 5:10am    
Add inside the class, e.g: public class A{//My code here}
Dalek Dave 8-Jan-11 8:26am    
Good 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