繁体   English   中英

如何知道特定文本框中是否有更改,该文本框是在C#中动态创建的

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM