如何从ASP.NET中动态创建的文本框中获取数据

时间:2018-03-06 10:05:46

标签: c# asp.net

我通过从MySQL获取数据来动态创建文本框。假设我在DB表格中有2行,ABC和XYZ则成功创建了2个文本框,但现在我想获取数据并对其进行一些操作。我将ID设置为TB1,TB2等文本框,但在检查工具中,ID类似于ContentPlaceHolder2_TB1,ContentPlaceHolder2_TB2。

我从here获得了一些类似的解决方案,但它不会起作用。

这是我的代码:

while (reader.Read())
        {
            TextBox tf1 = new TextBox();
            Label lb1 = new Label();
            lb1.Text = reader.GetString("attribute_name")+":";
            lb1.Attributes["style"] = "color:#000;font-weight:800;";  
            tf1.ID = "TB"+c;
            tf1.Attributes["placeholder"] = reader.GetString("attribute_name");
            tf1.Attributes["class"] = "form-control";
            tf1.Attributes["style"] = "width:35%;border:2px solid #ccc;";
            div1.Controls.Add(lb1);
            div1.Controls.Add(tf1);
            c = c + 1;
        }

protected void BtnSave_Click(object sender, EventArgs e)
 {
    string s = ((TextBox)div1.Controls["ContentPlaceHolder2_TB1"]).Text;
 }

2 个答案:

答案 0 :(得分:1)

https://www.youtube.com/watch?v=3w2JkLcp-UA

首先使用此链接在SQl服务器上创建一个简单的数据库然后看到我认为您可以在此之后解决您的问题。

答案 1 :(得分:-1)

看看

Get Value Text of dynamically created TextBox in ASPNet using C and VBNet

这将满足您的需求。

foreach (TextBox textBox in div1. Controls.OfType<TextBox>())
{
    message += textBox.ID + ": " + textBox.Text + "\\n";
}

这将为您提供结果。