简体   繁体   中英

How to get value from textBox by its name?

I am trying to get value from textBox by its name using Control class? There is my code:

Control ctl = FindControl(this, "B1"); if (ctl is TextBox) listBox1.Items.Add(((TextBox)ctl).Text); //"B1" - it's textBox name

public static Control FindControl(Control parent, string ctlName)
    {
        foreach (Control ctl in parent.Controls)
        {
            if (ctl.Name.Equals(ctlName))
            {
                return ctl;
            }

            FindControl(ctl, ctlName);
        }
        return null;
    }

The problem is that the compiler does not go into the function. What could be the problem?

        public Form1()
        {
            InitializeComponent();
            B1.Text = "LOL";
            Control ctl = FindControl(this, "B1");
            if (ctl is TextBox)
                listBox1.Items.Add(((TextBox)ctl).Text);
        }
        public static Control FindControl(Control parent, string ctlName)
        {
            foreach (Control ctl in parent.Controls)
            {
                if (ctl.Name.Equals(ctlName))
                {
                    return ctl;
                }

                FindControl(ctl, ctlName);
            }
            return null;
        }

If you did it like in sample above then all be right.
I suppose you use Windows Froms.
PS I can't write a commentary because I haven't 50 reputation.
Correct Answer
If TextBoxes are on the FlowLayout then the parent is FlowLayout and you need use the FlowLayout name instead of "this" in line Control ctl = FindControl(this, "B1");. Because "this" it's the MainWindow control.

Try to use the ID property of the Control instance instead. I'm not sure the Name property is available for the Control class, if we are speaking about System.Web.UI namespace.

For WinForms, you'd just do:

        Control ctl = this.Controls.Find("B1", true).FirstOrDefault();
        if (ctl != null)
        {
            // use "ctl" directly:
            listBox1.Items.Add(ctl.Text); 

            // or if you need it as a TextBox, then cast first:
            if (ctl is TextBox)
            {
                TextBox tb = (TextBox)ctl;
                // ... do something with "tb" ...
                listBox1.Items.Add(tb.Text);
            }
        }

You don't need your own recursive search function...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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