Hello,
I have copied coding from your website for adding textbox dynamically as seen below. But it is create only 1 textbox. I want to create multiple textboxes on button and save data in database in asp.net vb not c#.
it should be display when project run like in single row[ listbox1, txtbox, listbox2, listbox3, txtbox1(datetime), txtbox2(datetime)].
After click add button it will be created another row with same txtboxes. Is this possible?
My VB Code is:
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub AddTextBox(sender As Object, e As EventArgs)
Dim index As Integer = pnlTextBoxes.Controls.OfType(Of TextBox)().ToList().Count + 1
Me.CreateTextBox("txtDynamic" & index)
End Sub
Private Sub _Default_PreInit(sender As Object, e As EventArgs) Handles Me.PreInit
Dim keys As List(Of String) = Request.Form.AllKeys.Where(Function(key) key.Contains("txtDynamic")).ToList()
Dim i As Integer = 1
For Each key As String In keys
Me.CreateTextBox("txtDynamic" & i)
i = i + 1
Next
End Sub
Private Sub CreateTextBox(id As String)
Dim txt As New TextBox()
txt.ID = id
pnlTextBoxes.Controls.Add(txt)
Dim lt As New Literal()
lt.Text = "<br />"
pnlTextBoxes.Controls.Add(lt)
End Sub
Protected Sub Save(sender As Object, e As EventArgs)
For Each textBox As TextBox In pnlTextBoxes.Controls.OfType(Of TextBox)()
Dim constr As String = "Data Source=DESKTOP-I63D6N1;Initial Catalog=Student;Integrated Security=True"
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("INSERT INTO tblStudent (Name) VALUES (@Name)")
cmd.Connection = con
cmd.Parameters.AddWithValue("@Name", textBox.Text)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
Next
End Sub
End Class
My html code is:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="pnlTextBoxes" runat="server"></asp:Panel>
<hr />
<asp:Button ID="btnAdd" runat="server" Text="Add New" OnClick="AddTextBox"/>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save"/>
</div>
</form>
</body>
</html>