Here’s a scenario. I have a Students table in my SQL Server database, with few columns in it. I just have a button control on my web page. I wish to create the textboxes programmatically using Asp.Net, with click of the button.
The textboxes, that I'll create, are based on the columns in the table (SQL Server), that is, when a user clicks the button on the web page, the program will extract the column names from the Students table and create the textboxes.
These are dynamically created input boxes. Therefore, I’ll use jQuery to extract values in the textboxes and call a Web Method using Ajax and save the data in database.
The table has four columns.
CREATE TABLE Students ( ID int IDENTITY(1,1) PRIMARY KEY, Name varchar(255) NOT NULL, Address varchar(255), Age int );
In the markup section, I have a button control, whose click event will call a code behind method, which will create the textboxes. Next, I have a <div> element that will act as a container to the textboxes. I also have another button (remains hidden) to submit the data.
<div class="main">
<div>
<asp:Button ID="bt" runat="server" Text="Create a Form" OnClick="createForm" />
</div>
<h2>Students Info</h2>
<div id="columns" runat="server"
style="height:auto;
width:300px;
overflow:auto;">
</div>
<input type="button" id="submit" value="Submit" runat="server" style="display:none;" />
</div>
Let us now write the code to create the textboxes through a program.
Create Multiple Textboxes (C#)
using System; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Web.UI.HtmlControls; public partial class SiteMaster : System.Web.UI.MasterPage { SqlConnection myConn = default(SqlConnection); const string sConnString = "Data Source=DNA;Persist Security Info=False;" + "Initial Catalog=DNA_Classified;User Id=sa;Password=demo;Connect Timeout=30;"; protected void createForm(object sender, EventArgs e) { using (SqlConnection con = new SqlConnection(sConnString)) { string sSQL = "SELECT Name FROM sys.columns " + "WHERE object_id = OBJECT_ID('dbo.Students')"; SqlCommand objComm = new SqlCommand(sSQL, con); con.Open(); SqlDataReader reader = objComm.ExecuteReader(); int iCnt = 0; // JUST A COUNTER. while (reader.Read()) { if (iCnt >= 1) { HtmlGenericControl ul = new HtmlGenericControl("ul"); ul.Attributes.Add("style", "margin:2px 0;padding:0;"); HtmlGenericControl liCol = new HtmlGenericControl("li"); HtmlGenericControl spanCol = new HtmlGenericControl("span"); spanCol.InnerHtml = reader["Name"].ToString(); liCol.Attributes.Add("style", "width:30%;float:left;"); liCol.Controls.Add(spanCol); // CREATE AN INSTANCE OF TEXTBOX. // WITH EVERY COLUMN NAME, WE'LL CREATE AND ADD A TEXTBOX. TextBox txt = new TextBox(); txt.ID = reader["Name"].ToString(); // ASSIGN A CLASS. WE'LL USE THE CLASS NAME TO EXTRACT DATA USING JQUERY. txt.CssClass = "fld"; HtmlGenericControl liTxt = new HtmlGenericControl("li"); liTxt.Attributes.Add("style", "width:auto;"); liTxt.Controls.Add(txt); // ADD THE NEWLY CREATED TEXTBOX TO A LIST. ul.Controls.Add(liCol); ul.Controls.Add(liTxt); columns.Controls.Add(ul); } iCnt = iCnt + 1; } submit.Attributes.Add("style", "display:block;float:right;margin:10px;"); } } }
Vb Code to Create Multiple Textboxes
Option Explicit On Imports System.Data.SqlClient Partial Class Site Inherits System.Web.UI.MasterPage Dim myConn As SqlConnection Const sConnString As String = "Data Source=DNA;Persist Security Info=False;" & _ "Initial Catalog=DNA_Classified;User Id=sa;Password=demo;Connect Timeout=30;" Protected Sub createForm(ByVal sender As Object, ByVal e As EventArgs) Using con As SqlConnection = New SqlConnection(sConnString) Dim sSQL As String = "SELECT Name FROM sys.columns " & _ "WHERE object_id = OBJECT_ID('dbo.Students')" Dim objComm As New SqlCommand(sSQL, con) con.Open() Dim reader As SqlDataReader = objComm.ExecuteReader() Dim iCnt As Integer = 0 While reader.Read If Val(iCnt) >= 1 Then Dim ul As New HtmlGenericControl("ul") ul.Attributes.Add("style", "margin:2px 0;padding:0;") Dim liCol As New HtmlGenericControl("li") Dim spanCol As New HtmlGenericControl("span") spanCol.InnerHtml = reader.Item("Name") liCol.Attributes.Add("style", "width:30%;float:left;") liCol.Controls.Add(spanCol) ' CREATE AN INSTANCE OF TEXTBOX. ' WITH EVERY COLUMN NAME, WE'LL CREATE AND ADD A TEXTBOX. Dim txt As New TextBox() txt.ID = reader.Item("Name") ' ASSIGN A CLASS. WE'LL USE THE CLASS NAME TO EXTRACT DATA USING JQUERY. txt.CssClass = "fld" Dim liTxt As New HtmlGenericControl("li") liTxt.Attributes.Add("style", "width:auto;") liTxt.Controls.Add(txt) ' ADD THE NEWLY CREATED TEXTBOX TO A LIST. ul.Controls.Add(liCol) ul.Controls.Add(liTxt) columns.Controls.Add(ul) End If iCnt = iCnt + 1 End While submit.Attributes.Add("style", "display:block;float:right;margin:10px;") End Using End Sub End Class
Run the application and you will see a button to create a form. Clicking the button will show you three empty textboxes (with a Submit button).
image
Now, we’ll write the Web Method, which will save the data extracted from the dynamically created textboxes. We’ll call the method through an Ajax Post method.
The method will take a string value as parameter. The values will be contents from the textboxes.
[System.Web.Services.WebMethod()] public static string addStudents(string val) { string functionReturnValue = null; try { using (SqlConnection con = new SqlConnection(sConnString)) { string sQuery = null; sQuery = "INSERT INTO dbo.Students (Name, Address, Age)" + "VALUES (" + HttpUtility.UrlDecode(val) + ")"; using (SqlCommand cmd = new SqlCommand(sQuery)) { cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); functionReturnValue = "Success"; } } } catch (Exception ex) { functionReturnValue = "There was an error"; } finally { } return functionReturnValue; }
<System.Web.Services.WebMethod()> _ Public Shared Function addStudents(ByVal val As String) As String Try Using con As SqlConnection = New SqlConnection(sConnString) Dim sQuery As String sQuery = "INSERT INTO dbo.Students (Name, Address, Age)" & _ "VALUES (" & HttpUtility.UrlDecode(val) & ")" Using cmd As SqlCommand = New SqlCommand(sQuery) With cmd .Connection = con con.Open() cmd.ExecuteNonQuery() con.Close() addStudents = "Success" End With End Using End Using Catch ex As Exception addStudents = "There was an error" Finally ' End Try Return addStudents End Function
Finally, we’ll write the script to make an Ajax call to our Web Method.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <script> $(document).ready(function () { BindControls(); }); // CALL A WEB METHOD TO SAVE DATA USING AJAX. function BindControls() { $('#submit').click(function () { saveTextValue(); }); var values = new Array(); function saveTextValue() { // WHILE CREATING THE TEXTBOXES THROUGH A CODE PROCEDURE, // WE HAVE ASSIGNED A CLASS NAME CALLED "fld" TO EACH TEXTBOX. // USING THE CLASS NAME, WE CAN EASILY EXTRACT VALUES FROM THE INPUT BOXES. $('.fld').each(function () { if (this.value != '') { values.push("'" + this.value + "'"); } }); if (values != '') { // ONCE WE HAVE ALL THE VALUES, MAKE THE CALL TO OUR WEB METHOD. $.ajax({ type: 'POST', url: 'https://localhost:53094/csharp/default.aspx/addStudents', data: "{'val':'" + escape(values) + "'}", dataType: 'json', headers: { "Content-Type": "application/json" }, success: function (response) { alert(response.d); // DONE. values = ''; }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown); } }); } else { alert("Fields cannot be empty.") } } } </script>