首页 > 解决方案 > 当我尝试使用按钮控件填充文本框时如何选择不同的文本框

问题描述

在此处输入图像描述

我正在尝试使用按钮控件在表单中填充两个文本框,但它似乎仅适用于 1。当我运行程序时,我无法在两个文本框之间进行选择。我应该使用什么条件?

private void Button0_Click(object sender, EventArgs e)
{
    if (???????????????????)
    {
        metroTextBoxQuantity.Text = metroTextBoxQuantity.Text + "0";
    }
    else
    {
        metroTextBoxItemcode.Text = metroTextBoxItemcode.Text + "0";
    }
}

标签: c#winforms

解决方案


一种可能的解决方案是创建一个Control变量来存储对最后单击的文本框的引用。这将由Click两个文本框的事件处理。然后,在您单击数字按钮时,只需将数字附加到选定的文本框变量即可。像这样的东西:

Control SelectedTextbox { get; set; } = null;

//Use this event handler for both the Quantity and Itemcode textbox
public TextBox_Click(object sender, EventArgs e)
{
    SelectedTextbox = (Control)sender;
}

private void Button0_Click(object sender, EventArgs e)
{
    if(SelectedTextbox == null)
        throw new Exception("SelectedTextbox has not been set");
    SelectedTextbox.Text += "0";
}

请注意,如果MetroTextBox不继承自Control,则需要更改SelectedTextbox为其他类型。不过,它很可能确实如此。

您可能还需要考虑对所有按钮单击使用单个事件处理程序,而不是每次单击一个事件处理程序。您可以使用sender的名称解析单击了哪个数字按钮,也可以将按钮的编号存储在按钮中Tag并从那里读取。但这最好留给另一个问题。


推荐阅读