【问题标题】:How to get value from textBox by its name?如何通过名称从 textBox 中获取价值?
【发布时间】:2015-08-04 15:26:01
【问题描述】:

我正在尝试使用 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;
    }

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

【问题讨论】:

  • 您使用什么语言和环境?
  • Visual Studio 2010 中的 C#
  • 在您的问题中添加 c# 标签,以便人们更好地回答您的问题
  • 可以加前端标记吗?
  • 这是 WinForms 吗?网络表单?还有什么?...

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


【解决方案1】:
        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 声望。
正确答案
如果 TextBoxes 在 FlowLayout 上,则父级是 FlowLayout,您需要在 Control ctl = FindControl(this, "B1"); 行中使用 FlowLayout 名称而不是“this”。因为“this”是 MainWindow 控件。

【讨论】:

  • 是的,我使用的是 Windows 窗体。
  • 在您使用 FindControl(Control, String) 函数的地方放置一个断点。可能是返回null?
  • 如果TextBoxes放在FlowLayuot面板上说明编译器不进入函数,但是如果TextBoxes只放在窗体上就可以了。如何解决这个问题?
  • 如果 TextBoxes 在 FlowLayout 上,那么父级是 FlowLayout 并且您需要在 Control ctl = FindControl(this, "B1"); 行中使用 FlowLayout 名称而不是“this”。因为“this”是 MainWindow 控件。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-15
      • 2021-07-24
      • 2017-09-05
      • 2015-06-19
      • 2013-03-23
      • 2011-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多