【问题标题】:How Do I Insert Dynamically Created Textbox Values To Database如何将动态创建的文本框值插入数据库
【发布时间】:2014-11-03 09:34:14
【问题描述】:

这是我创建动态文本框的代码..我想将这些值插入数据库

我需要将动态创建的文本框值插入到数据库中。我该怎么做..我是 asp.net 的新手

标记:

<div>
    <asp:Panel ID="Panel1" runat="server" Width="300px" />
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>

代码隐藏:

protected void Page_load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        //Remove the session when first time page loads.
        Session.Remove("clicks");
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    int rowCount = 0;

    //initialize a session.
    rowCount = Convert.ToInt32(Session["clicks"]);

    rowCount++;

    //In each button clic save the numbers into the session.
    Session["clicks"] = rowCount;

    //Create the textboxes and labels each time the button is clicked.
    for (int i = 0; i < rowCount; i++)
    {
        TextBox TxtBoxU = new TextBox();          
        Label lblU = new Label();          
        TxtBoxU.ID = "TextBoxU" + i.ToString();            
        lblU.ID = "LabelU" + i.ToString();         
        lblU.Text = "Category Name " + (i + 1).ToString() + " : ";

        //Add the labels and textboxes to the Panel.
        Panel1.Controls.Add(lblU);
        Panel1.Controls.Add(TxtBoxU);
    }
}

【问题讨论】:

  • 您使用的是什么数据库,您是如何与之通信的?
  • 我正在使用 ms sql server 数据库..
  • 我的表名是Category,字段是CategoryID,CategoryName
  • 我强烈反对在 ASP.NET Web 表单应用程序中生成动态控件,因为在回发期间保留它们总是很痛苦。如果你真的需要提供这样的功能,那就继续使用 ASP.NET MVC 甚至 ASP.NET MVC SPA,生活会更轻松,你的代码也可以管理

标签: c# asp.net


【解决方案1】:

我认为您无法访问文本框的值,通过它您可以轻松访问该值。 并且我希望你知道如何将数据插入数据库。

   for (int i = 0; i < rowCount; i++)
            {
                string OptionID = "TextBoxU" + i;
                TextBox tb = (TextBox)Panel1.FindControl(OptionID);

             /******** USe the tb.Text value to get 
                    the value and then store it into Database**********/
            }

【讨论】:

  • 我收到一个错误...对象引用未设置为 oblect 的实例...请帮助
  • 你必须在每个回帖中添加动态控件,所以...在 PageLoad 中添加控件,然后只有它可以在 buttonclick 中访问。
  • 但我在添加按钮点击中创建了动态文本框
  • 将按钮单击的整个代码(用于添加动态控件)放在一个方法中,并从按钮单击和从 pageLoad 调用该方法。
  • 谢谢 Kumod....你能运行上面的代码吗...如果我在文本框中输入值并添加另一个文本框,上面的值会丢失...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-05
  • 1970-01-01
  • 2013-12-18
  • 2014-04-20
  • 2021-10-29
  • 2017-08-23
相关资源
最近更新 更多