[英]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? 我想动态添加文本框并将这些值保存到asp.net中的数据库中,asp.net中是否对此有任何控件?
how can I do this in asp.net? 我如何在asp.net中做到这一点?
To add dynamic control in your .aspx file below is sample code. 在下面的.aspx文件中添加动态控件的示例代码。
Add below div in your .aspx file with id which is addControl 在.aspx文件中的div下面添加ID为addControl的div
<div id="addControl" runat="server">
</div>
You can create dynamic TextBox control by adding below code in you .cs file. 您可以通过在.cs文件中添加以下代码来创建动态TextBox控件。 Add Control is a id of above define div. 添加控件是上面定义div的ID。
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,您可以获取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. NameValueCollection表示关联的String键和String值的集合,可以通过键或索引来访问它们。
You can use the Panel to create the Dynamic Text box. 您可以使用面板创建“动态文本”框。 Panel pnlTextBox; 面板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# C#
protected void Save(object sender, EventArgs e) 受保护的无效Save(对象发送者,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 正如您在评论中提到的那样,您正在使用Jquery,因此为了在回发期间加载它,请尝试在
function pageLoad() {// your dynamic Text box code using Jquery}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.