如何通过名称从textBox获取值?

时间:2015-08-04 15:26:01

标签: c# .net visual-studio textbox controls

我试图通过使用Control类的名称从textBox获取值? 有我的代码:

Control ctl = FindControl(this, "B1"); if (ctl is TextBox) listBox1.Items.Add(((TextBox)ctl).Text); //" B1" - 它的文本框名称

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

问题是编译器没有进入该函数。 可能是什么问题?

3 个答案:

答案 0 :(得分:0)

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

如果你像上面的样本那样做,那么一切都是正确的。
我想你使用的是Windows Froms 附:我不能写评论,因为我没有50的声誉 正确答案
如果TextBox在FlowLayout上,则父级是FlowLayout,您需要使用FlowLayout名称而不是"这个" in line Control ctl = FindControl(this," B1");.因为"这个"它是MainWindow控件。

答案 1 :(得分:0)

尝试使用Control实例的ID属性。如果我们谈论System.Web.UI命名空间,我不确定Control属性的Name属性是否可用。

答案 2 :(得分:0)

对于WinForms,你只需:

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

您不需要自己的递归搜索功能......

相关问题