简体   繁体   English

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

[英]How to know if there is a changes in a specific textbox, the textbox is dynamically created in C#

I want to put a value in other dynamically created textbox if there is a changes in a specific textbox that was also dynamically created. 如果要动态创建的特定文本框中发生更改,我想在其他动态创建的文本框中添加一个值。 How could I possibly do this? 我怎么可能这样做?

this is how i created the textbox: 这就是我创建文本框的方式:

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

Here is the output of it: 这是它的输出:

在此处输入图片说明

Example if I put a value to the Mag Data, it will also pass the value to Card Number and Exp Date. 例如,如果我在Mag Data中输入了一个值,它也会将该值传递给Card Number和Exp Date。 How could I possibly do this? 我怎么可能这样做?

You can dynamically add an event handler to your Dynamic TextBox's TextChanged Event and since you are also using your Field Names as your TextBox Name you can cast your events sender object to determine which TextBox was changed. 您可以将事件处理程序动态添加到动态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
    }
}

The issue that you are having is that your Name Property is not accessable as a TextBox ie you can not do "Card Number".Text you will need to search the Control Collection for the TextBox named "Card Number" you can use the Controls.Find Method to do so. 您遇到的问题是您的Name属性不能作为TextBox访问,即您不能执行“卡号”。您需要在控件集合中搜索名为“卡号”的文本框的文本,然后才能使用控件。查找方法这样做。

ie

if (tb.Name == "Mag Data")
{
    Control[] cntrl = Controls.Find("Card Number", true);
    if (cntrl.Length != 0)
    {
        ((TextBox)cntrl[0]).Text = tb.Text;
    }
}

Add an event handler to the textbox: 将事件处理程序添加到文本框:

txt.TextChanged += (sender, args) => {
    // Logic to update other textboxes
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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