Home > OS >  How to apply a Focus() function on Dynamically Created TextBox in windows forms?
How to apply a Focus() function on Dynamically Created TextBox in windows forms?

Time:09-13

When dynamically creating textBoxes how can we make one of the textBoxes have the Focus() function on it?

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

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 1; i <= 5; i  )
            {
                TextBox txt = new TextBox();
                Point txtKonum = new Point(300, i * 30);
                txt.Location = txtKonum;
                txt.Name = "TextBox"   i;
                txt.Text = i.ToString();
                this.Controls.Add(txt);
            }
        }
    }
}

Simply writing TextBox4.Focus() into the for loop is not working.

for (int i = 1; i <= 5; i  )
            {
                TextBox txt = new TextBox();
                Point txtKonum = new Point(300, i * 30);
                txt.Location = txtKonum;
                txt.Name = "TextBox"   i;
                txt.Text = i.ToString();
                if(i == 4)
                {
                    txt.Focus();
                }
                this.Controls.Add(txt);
            }

This code does not work either. enter image description here

As you can see in the picture there is no cursor on the 4th textBox.

CodePudding user response:

Solved, just put the this.Controls.Add(txt); code before the if statement,

            {
                TextBox txt = new TextBox();
                Point txtKonum = new Point(300, i * 30);
                txt.Location = txtKonum;
                txt.Name = "TextBox"   i;
                txt.Text = i.ToString();
                this.Controls.Add(txt);
                if(i == 4)
                {
                    txt.Focus();
                }

            } 

CodePudding user response:

Try giving control after the loop has completed:

private void button1_Click(object sender, EventArgs e)
{
    for (int i = 1; i <= 5; i  )
    {
        TextBox txt = new TextBox();
        Point txtKonum = new Point(300, i * 30);
        txt.Location = txtKonum;
        txt.Name = "TextBox"   i;
        txt.Text = i.ToString();
        this.Controls.Add(txt);
    }
    this.ActiveControl = this.TextBox4
}
  • Related