我用代码自动生成几个文本框,想实现这么一个功能,当第一个文本框输入的文本长度一定时,焦点自动到下一个文本框,以下是我的代码,没写完全,希望大家指点一下。private void Form1_Load(object sender, EventArgs e)
{
int x = 10;
int y = 5;
for (int i = 0; i < 5; i++)
{
TextBox tb = new TextBox();
tb.Name = "tb" + i;
tb.Location = new System.Drawing.Point(x, y);
tb.Size = new System.Drawing.Size(60, 20);
tb.GotFocus+=new EventHandler(tb_GotFocus); panel1.Controls.Add(tb);
y += 25;
}
} private void tb_GotFocus(object sender, EventArgs e)
{
foreach (Control c in panel1.Controls)
{
if (c is TextBox&&c.Focused==true)
{
}
}
}
{
int x = 10;
int y = 5;
for (int i = 0; i < 5; i++)
{
TextBox tb = new TextBox();
tb.Name = "tb" + i;
tb.Location = new System.Drawing.Point(x, y);
tb.Size = new System.Drawing.Size(60, 20);
tb.GotFocus+=new EventHandler(tb_GotFocus); panel1.Controls.Add(tb);
y += 25;
}
} private void tb_GotFocus(object sender, EventArgs e)
{
foreach (Control c in panel1.Controls)
{
if (c is TextBox&&c.Focused==true)
{
}
}
}
foreach (Control c in panel1.Controls)
{
if (c is TextBox&&[条件])
{
flag = true;
}
if(flag){c.Focus = true; break;}
}
{
int x = 10;
int y = 5;
for (int i = 0; i < 5; i++)
{
TextBox tb = new TextBox();
tb.Name = "tb" + i;
tb.Location = new System.Drawing.Point(x, y);
tb.Size = new System.Drawing.Size(60, 20);
tb.TabIndex = i;//最好是设置一下它的TabIndex
tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);
//tb.GotFocus += new EventHandler(tb_GotFocus);
this.Controls.Add(tb);//把这里的'this'换成你的panel1
y += 25;
}
} private void tb_KeyPress(object sender, KeyPressEventArgs e)
{
TextBox tb=((TextBox)sender);
if(tb.Text.Length==4)
{
int count = this.Controls.Count;
int index = tb.TabIndex;
if (index == 4)
this.Controls[0].Focus();//把这里的'this'换成你的panel1 else
this.Controls[index + 1].Focus();//把这里的'this'换成你的panel1 }
}
我试了的 这样可以实现你要的效果……。。
是KeyPress
在KeyPress事件处理程序中判断当前文本框的字符长度(text1.Text.Length)是否超过预设值