c# - 当我尝试使用按钮控件填充文本框时如何选择不同的文本框
问题描述
我正在尝试使用按钮控件在表单中填充两个文本框,但它似乎仅适用于 1。当我运行程序时,我无法在两个文本框之间进行选择。我应该使用什么条件?
private void Button0_Click(object sender, EventArgs e)
{
if (???????????????????)
{
metroTextBoxQuantity.Text = metroTextBoxQuantity.Text + "0";
}
else
{
metroTextBoxItemcode.Text = metroTextBoxItemcode.Text + "0";
}
}
解决方案
一种可能的解决方案是创建一个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
并从那里读取。但这最好留给另一个问题。
推荐阅读
- nim-lang - Nim-Lang:如何在过程中接受任意数量的参数
- javascript - 从一个数组中获取一些不同的随机元素,(每次不设置不同的变量)
- python - Subprocess.popen - 如何一次只运行一个进程
- node.js - 使用nodejs格式化对象数组
- javascript - 函数接收来自两个不同来源的参数
- android - Android Widget按钮服务不响应点击
- django-models - 在 Django 模型中反转外键关系会导致问题吗?
- c++ - 在堆栈c ++中推送弹出顶部
- javascript - 在 Angular 10 中生成由节点组成的响应式网格
- jupyter - 奇点容器中的 Jupyter 笔记本