[英]How to know if there is a changes in a specific textbox, the textbox is dynamically created in C#
如果要动态创建的特定文本框中发生更改,我想在其他动态创建的文本框中添加一个值。 我怎么可能这样做?
这就是我创建文本框的方式:
for (int x = 0; x < dt.Rows.Count; x++)
{
TextBox txt = new TextBox();
txt.Name = dt.Rows[x]["field_name"].ToString();
txt.Text = txt.Name;
txt.Width = 200;
var margintx = txt.Margin;
margintx.Bottom = 5;
txt.Margin = margintx;
flowLayoutPanelText.Controls.Add(txt);
}
这是它的输出:
例如,如果我在Mag Data中输入了一个值,它也会将该值传递给Card Number和Exp Date。 我怎么可能这样做?
您可以将事件处理程序动态添加到动态TextBox's
TextChanged事件中,并且由于还使用Field
名作为TextBox
名称,因此可以转换事件发送者对象,以确定更改了哪个TextBox
。
for (int x = 0; x < dt.Rows.Count; x++)
{
TextBox txt = new TextBox();
txt.TextChanged += new EventHandler(txt_TextChanged);
txt.Name = dt.Rows[x]["field_name"].ToString();
txt.Text = txt.Name;
txt.Width = 200;
var margintx = txt.Margin;
margintx.Bottom = 5;
txt.Margin = margintx;
flowLayoutPanelText.Controls.Add(txt);
}
void txt_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
if (tb.Name == "Mag Data")
{
//Do Stuff Here
}
}
您遇到的问题是您的Name
属性不能作为TextBox
访问,即您不能执行“卡号”。您需要在控件集合中搜索名为“卡号”的文本框的文本,然后才能使用控件。查找方法这样做。
即
if (tb.Name == "Mag Data")
{
Control[] cntrl = Controls.Find("Card Number", true);
if (cntrl.Length != 0)
{
((TextBox)cntrl[0]).Text = tb.Text;
}
}
将事件处理程序添加到文本框:
txt.TextChanged += (sender, args) => {
// Logic to update other textboxes
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.