-2

我正在尝试制作一个小型应用程序,以使我的工作更容易通过 WinForms C# 创建定义(新的 Web 表单 aspx)。

现在我有了这个表单,我在其中告诉应用程序我想创建多少个文本框。

创建后,我想将我编写的文本框值分配给一个字符串。

    private void CreateControls()
    {
        for (int index = 0; index < NumberOfRows; index++)
        {
            TextBox textBox = new TextBox();
            textBox.Name = "TextBox" + (index + 1).ToString();
            textBox.Size = new Size(120, 20);
            textBox.Location = new Point(X, Y + 26);

            ComboBox comboBox = new ComboBox();
            comboBox.Name = "ComboBox" + (index + 1).ToString();
            comboBox.Size = new Size(75, 20);
            comboBox.Location = new Point(141, Y + 26);
            comboBox.DataSource = Enum.GetNames(typeof(DataTypes));

            Y += 26;

            this.Controls.Add(textBox);
            this.Controls.Add(comboBox);
        }
    }

现在,我不知道如何检查文本框是否已创建,然后获取它们的值。

任何人都可以向我推荐一些东西吗?谢谢 :)!

4

2 回答 2

2

您需要找到这些控件并获取它们的值Page_Load。由于您在创建它们时给了它们有意义的名称,因此这应该可以解决问题:

for (int index = 0; index < NumberOfRows; index++)
{
    TextBox textBox = this.FindControl(
        string.Format("TextBox{0}", index)) as TextBox;
    if (textBox == null) { continue; }  // this means it wasn't found

    var text = textBox.Text;
    // work with the text
}

但是,如果ComboBox您使用的类不是第三方类,也不是 ASP.NET 应用程序,则代码也适用于 Windows 窗体应用程序,只需稍作修改:

for (int index = 0; index < NumberOfRows; index++)
{
    // you have to use the Find method of the ControlCollection
    TextBox textBox = this.Controls.Find(
        string.Format("TextBox{0}", index)) as TextBox;
    if (textBox == null) { continue; }  // this means it wasn't found

    var text = textBox.Text;
    // work with the text
}

我倾向于同意社区的观点,即它可能是一个 Windows 窗体应用程序,因为您无法设置Location标准ASP.NET控件。但是,如果这些是支持这些属性并呈现适当 CSS 的用户控件或第三方控件,那么我们永远不会知道。

于 2013-09-17T13:38:13.813 回答
0
if(Page.FindControl("IDofControl") != null)
   //exists
else
   //does no exists
于 2013-09-17T13:40:18.720 回答