单击相同的按钮但操作不同 - c#

Clicking the same button but different action - c#

当我单击一个按钮时,文本将出现在文本框 1 中,但随后我希望它将焦点更改为另一个文本框 (textbox2),当我再次单击同一个按钮时,显示相同的文本但在文本框 2 中。

    private void btna_Click(object sender, EventArgs e)
    {
        textBox1.Text = ("A");
        if (textBox1.Text.Length > 0)
        {
            textBox2.Focus();
        }

如果你想在点击事件中切换不同的文本框来决定更新哪一个,你可以在一个私有变量中跟踪它们,然后根据当前值切换你正在使用的文本框,因为示例:

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;
}