简体   繁体   中英

how to add textbox dynamically and save in asp.net

I want to add textboxes dynamically and save these values to database in asp.net, Is there any controls for this in asp.net?

how can I do this in asp.net?

To add dynamic control in your .aspx file below is sample code.

Add below div in your .aspx file with id which is addControl

<div id="addControl" runat="server">
</div>

You can create dynamic TextBox control by adding below code in you .cs file. Add Control is a id of above define div.

 TextBox txt1 = new TextBox();
 txt1.ID = "txtOne";
 txt1.Text = "";
 txt1.CssClass = "myClass";
 txt1.ClientIDMode = System.Web.UI.ClientIDMode.Static;
 addControl.Controls.Add(txt1);

With the help of NameValueCollection you can get the value of TextBox.

NameValueCollection frmCollection = Request.Form;
string inputString = frmCollection["txtOne"];

NameValueCollection represents a collection of associated String keys and String values that can be accessed either with the key or with the index.

You can use the Panel to create the Dynamic Text box. Panel pnlTextBox;

protected void Page_PreInit(object sender, EventArgs e)
{
    //Create a Dynamic Panel
    pnlTextBox = new Panel();
    pnlTextBox.ID = "pnlTextBox";
    pnlTextBox.BorderWidth = 1;
    pnlTextBox.Width = 300;
    this.form1.Controls.Add(pnlTextBox);

    //Create a LinkDynamic Button to Add TextBoxes
    LinkButton btnAddtxt = new LinkButton();
    btnAddtxt.ID = "btnAddTxt";
    btnAddtxt.Text = "Add TextBox";
    btnAddtxt.Click += new System.EventHandler(btnAdd_Click);
    this.form1.Controls.Add(btnAddtxt);

    //Recreate Controls
    RecreateControls("txtDynamic", "TextBox");
}

For saving to DB:

<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" />

C#

protected void Save(object sender, EventArgs e)

{

        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO Names(Name) VALUES(@Name)"))
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@Name", txtDynamic.Text);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }

}

For More details please refer this link

Edit

As you mentioned in your Comments that you are using Jquery , so in order to load that during the postbacks try to load the Textbox in

function pageLoad() {// your dynamic Text box code using Jquery}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM