当我单击一个按钮时,文本将出现在textbox1中,但随后我希望它将焦点更改为另一个文本框(textbox2),并且当我再次单击同一按钮时,在textbox2中显示相同的文本。
private void btna_Click(object sender, EventArgs e)
{
textBox1.Text = ("A");
if (textBox1.Text.Length > 0)
{
textBox2.Focus();
}
答案 0 :(得分:0)
如果要在单击事件中的不同文本框之间交替以确定要更新的文本框,可以在私有变量中跟踪它们,然后仅根据当前值切换要使用的文本框,例如:
private TextBox textBoxToUpdate = null;
private void button1_Click(object sender, EventArgs e)
{
// Swap the textBoxToUpdate between textBox1 and textBox2 each time
textBoxToUpdate = (textBoxToUpdate == textBox1) ? textBox2 : textBox1;
textBoxToUpdate.Text = "A";
}
如果要更新多个控件,另一种方法是将它们存储在列表中,并增加一个整数,该整数定义下一项的索引。
// holds the text boxes we want to rotate between
private List<TextBox> textBoxesToUpdate = new List<TextBox>();
private void Form1_Load(object sender, System.EventArgs e)
{
// add some text boxes to our list
textBoxesToUpdate.Add(textBox1);
textBoxesToUpdate.Add(textBox2);
textBoxesToUpdate.Add(textBox3);
textBoxesToUpdate.Add(textBox4);
}
// stores the index of the next textBox to update
private int textBoxToUpdateIndex = 0;
private void button1_Click(object sender, EventArgs e)
{
textBoxesToUpdate[textBoxToUpdateIndex].Text = "A";
// increment the index but set it back to zero if it's equal to the count
if(++textBoxToUpdateIndex == textBoxesToUpdate.Count) textBoxToUpdateIndex = 0;
}