Add dynamic textbox and save values to database in Asp.Net using C#. - CodingPot | Programming Blog - ASP.NET, C#, VB.NET, AngularJs, SQL Server, AJAX, JQuery Tutorials.

Monday, 24 February 2020

Add dynamic textbox and save values to database in Asp.Net using C#.

In this article I will explain “How to add dynamic textbox and save values to database in Asp.Net using C#” with an example. I have used Bootstrap, Css, and JavaScript for Better User Interface and functionality. In between development sometimes we have to add dynamic forms, controls, any other things. Basically dynamic forms, dynamic controls functionality is use in Payroll system, Attendance system or any more other system. So if you want to add dynamic textbox on run time site then you are stay on right site.

How to add dynamic textbox and save values to database in Asp.Net using C#

Let’s go with an example

Just follow the following steps to implement “Dynamic textbox and save values to database”.

In this article, we have used Visual Studio 2015, Asp.Net Technology, JavaScript and SQL Server Management Studio.

Database and Tables

I have made the following tables with this script as follows.

Tbl_Employee


CREATE TABLE [dbo].[Tbl_Employee]( [ID] [int] IDENTITY(1,1) NOT NULL, [FirstName] [nvarchar](50) NULL, [LastName] [nvarchar](50) NULL, [Address] [nvarchar](max) NULL, [City] [nvarchar](50) NULL, [State] [nvarchar](50) NULL, [Total_Payment] [decimal](18, 2) NULL, [PaymentCount] [int] NULL, CONSTRAINT [PK_Tbl_Employee] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO

Tbl_ReceivePayment


CREATE TABLE [dbo].[Tbl_ReceivePayment]( [ID] [int] IDENTITY(1,1) NOT NULL, [Employee_Id] [int] NULL, [RowIndex] [int] NULL, [ColIndex] [int] NULL, [Payment] [decimal](18, 2) NULL, CONSTRAINT [PK_Tbl_ReceivePayment] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO

Download Script

Create one new empty project with proper project name and then add 2 new pages (EmployeeList.aspx, Employee.aspx,) with pages names. In Employee List Page we will listing the all saved employees with details button. On details button click redirect to details page and data will be bind on controls. On details page Submit button is bottom of form. On Submit button click the employee and payment data save/update and redirect on employee list page.

Namespaces

You will need to import the following namespaces in both pages.

using System; using System.Collections.Generic; using System.Linq; using System.Web.UI.WebControls; using DynamicControl.Model;

Before going to coding we have to add Db Model Edmx in project. So create one folder “Model” in project. Right click on Model folder and Add New Item. On the popup box Left side select Data option and then select “ADO.NET Entity Data Model” from the center panel and click on “Add” button. Select the data source and then tables (Tbl_Employee, Tbl_ReceivePayment) those are useable for our project. After adding Edmx file double click on the Edmx file. The Edmx file is look like below.

Model1

In this article practical we used LINQ so we added above Entity Model and for Database operation we will use entity name “Test Entities” that we had written when we added Edmx file. For the Database related operation we need this entity. Let’s add code in Employee List and Employee Page.

EmployeeList.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EmployeeList.aspx.cs" Inherits="DynamicControl.EmployeeList" %> <!DOCTYPE html> <html xmlns="https://www.w3.org/1999/xhtml"> <head runat="server"> <title>Employee List</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <form id="form1" runat="server"> <style type="text/css"> th,tr,td { text-align: center; } </style> <div class="form-horizontal"> <div class="row"> <div class="col-md-4"> </div> <div class="col-md-4"> <center><h4 class="heading">Employee List</h4></center> </div> <div class="col-md-4" style="text-align: center; padding-top: 5px"> <asp:Button ID="btnNewEmployee" runat="server" Text="New Employee" CssClass="btn btn-info" OnClick="btnNewEmployee_Click" /> </div> </div> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-7" style="text-align: center"> <asp:ListView ID="lvEmployees" runat="server" OnItemCommand="lvEmployees_ItemCommand" GroupPlaceholderID="groupplaceholder" ItemPlaceholderID="itemplaceholder"> <LayoutTemplate> <table border="1"> <tr> <th>First Name </th> <th>Last Name </th> <th>Address </th> <th>City </th> <th>State </th> <th>Total Payment </th> <th>Action </th> </tr> <tr id="groupplaceholder" runat="server"> </tr> </table> </LayoutTemplate> <GroupTemplate> <tr> <tr id="itemplaceholder" runat="server"></tr> </tr> </GroupTemplate> <ItemTemplate> <td> <%# Eval("FirstName") %> </td> <td> <%# Eval("LastName") %> </td> <td> <%# Eval("Address") %> </td> <td> <%# Eval("City") %> </td> <td> <%# Eval("State") %> </td> <td> <%# Eval("Total_Payment") %> </td> <td> <asp:Button ID="btnDetails" runat="server" Text="Details" CommandName="GetData" CommandArgument='<%# Eval("ID") %>'></asp:Button> </td> </ItemTemplate> </asp:ListView> </div> <div class="col-md-2"> </div> </div> <div class="row"> </div> </div> </form> </body> </html>

EmployeeList.aspx.cs


using System; using System.Collections.Generic; using System.Linq; using System.Web.UI.WebControls; using DynamicControl.Model; namespace DynamicControl { public partial class EmployeeList : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { bindEmployeeList(); } } protected void bindEmployeeList() { TestEntities objTestEntity = new TestEntities(); List<Tbl_Employee> employeeList = objTestEntity.Tbl_Employee.ToList(); lvEmployees.DataSource = employeeList; lvEmployees.DataBind(); } protected void lvEmployees_ItemCommand(object sender, ListViewCommandEventArgs e) { try { if (e.CommandName == "GetData") { if (e.CommandSource is Button) { ListViewDataItem item = (e.CommandSource as Button).NamingContainer as ListViewDataItem; Button button = item.FindControl("btnDetails") as Button; string ID = button.CommandArgument; Response.Redirect(string.Format("~/Employee.aspx?ID={0}", ID)); } } } catch (Exception ex) { } } protected void btnNewEmployee_Click(object sender, EventArgs e) { try { Response.Redirect(string.Format("~/Employee.aspx?ID={0}", 0)); } catch (Exception) { } } } }

In above EmployeeList.aspx page list out all employees with detail option button. For the Better User Interface we have used cdn Bootstrap link and Jquery. On top of the page Right side added one Button “Add Employee”. On click of this button redirect to Employee detail page there all controls are currently blank because we will go there for add new employee. The page is look like below.

EmployeeListImage

Employee.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Employee.aspx.cs" Inherits="DynamicControl.Employee" %> <!DOCTYPE html> <html xmlns="https://www.w3.org/1999/xhtml"> <head runat="server"> <title>Employee Details</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <form id="form1" runat="server"> <script> function addPayment() { var number = document.getElementById("<%= hidNoOfPayment.ClientID %>").value; if (number) { } else { number = "0"; } debugger; var count = parseInt(number, 10) + 1; document.getElementById("<%= hidNoOfPayment.ClientID %>").value = (count); } </script> <asp:HiddenField runat="server" ID="hidNoOfPayment" /> <asp:Label ID="lblEmployeeId" runat="server" Visible="false"></asp:Label> <asp:TextBox ID="TextBox" runat="server" Visible="false" OnTextChanged="TextBox_TextChanged"></asp:TextBox> <div class="form-horizontal"> <div class="row"> <div class="col-md-4"> </div> <div class="col-md-4"> <div class="row"> <center><h4 class="heading">Employee Details</h4></center> </div> <div class="row"> <div class="form-group"> <asp:Label ID="lblFirstName" CssClass="control-label col-sm-3" runat="server" Text="First Name"></asp:Label> <div class="col-md-6"> <asp:TextBox ID="txtFirstName" runat="server" CssClass="form-control"></asp:TextBox> </div> </div> </div> <div class="row"> <div class="form-group"> <asp:Label ID="lblLastName" CssClass="control-label col-sm-3" runat="server" Text="Last Name"></asp:Label> <div class="col-md-6"> <asp:TextBox ID="txtLastName" runat="server" CssClass="form-control"></asp:TextBox> </div> </div> </div> <div class="row"> <div class="form-group"> <asp:Label ID="lblState" CssClass="control-label col-sm-3" runat="server" Text="State"></asp:Label> <div class="col-md-6"> <asp:TextBox ID="txtState" runat="server" CssClass="form-control"></asp:TextBox> </div> </div> </div> <div class="row"> <div class="form-group"> <asp:Label ID="lblCity" CssClass="control-label col-sm-3" runat="server" Text="City"></asp:Label> <div class="col-md-6"> <asp:TextBox ID="txtCity" runat="server" CssClass="form-control"></asp:TextBox> </div> </div> </div> <div class="row"> <div class="form-group"> <asp:Label ID="lblAddress" CssClass="control-label col-sm-3" runat="server" Text="Address"></asp:Label> <div class="col-md-6"> <asp:TextBox ID="txtAddress" runat="server" CssClass="form-control"></asp:TextBox> </div> </div> </div> <div class="row"> <div class="form-group"> <div class="col-sm-3"> </div> <div class="col-md-6"> <asp:Button ID="btnAddPayment" OnClientClick="addPayment()" CssClass="btn btn-primary" runat="server" Text=" + Add Payment" OnClick="btnAddPayment_Click" /> </div> </div> </div> <div class="row"> <asp:Panel ID="pnlPayment" runat="server" ScrollBars="Auto"> <asp:Table runat="server" ID="tblPayment" class="table"> </asp:Table> </asp:Panel> </div> <div class="row"> <div class="form-group"> <asp:Label ID="lblTotal" CssClass="control-label col-sm-3" runat="server" Text="Total"></asp:Label> <div class="col-md-6"> <asp:TextBox ID="txt_Total" runat="server" CssClass="form-control"></asp:TextBox> </div> </div> </div> <div class="row"> <div class="form-group"> <div class="col-sm-3"> </div> <div class="col-md-6"> <asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="btn btn-success" OnClick="btnSubmit_Click" /> </div> </div> </div> </div> <div class="col-md-4"> </div> </div> </div> </form> </body> </html>

Employee.aspx.cs


using System; using System.Collections.Generic; using System.Linq; using System.Web.UI.WebControls; using DynamicControl.Model; namespace DynamicControl { public partial class Employee : System.Web.UI.Page { bool isPaymentTableCreated = false; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Request.QueryString["ID"] != "") { TestEntities objTestEntity = new TestEntities(); long employeeId = 0; lblEmployeeId.Text = Request.QueryString["id"]; FillEmployeeDetails(); } } if (isPaymentTableCreated == false) { if (!string.IsNullOrEmpty(hidNoOfPayment.Value)) { GeneratePaymentTable(Convert.ToInt32(hidNoOfPayment.Value)); } } } private void FillEmployeeDetails() { try { TestEntities objTestEntity = new TestEntities(); var employeeId = Convert.ToInt32(lblEmployeeId.Text); var objData = objTestEntity.Tbl_Employee.Where(a => a.ID == employeeId).FirstOrDefault(); if (objData != null) { if (!string.IsNullOrEmpty(objData.FirstName)) { txtFirstName.Text = objData.FirstName; } if (!string.IsNullOrEmpty(objData.LastName)) { txtLastName.Text = objData.LastName; } if (!string.IsNullOrEmpty(objData.State)) { txtState.Text = objData.State; } if (!string.IsNullOrEmpty(objData.City)) { txtCity.Text = objData.City; } if (!string.IsNullOrEmpty(objData.Address)) { txtAddress.Text = objData.Address; } if (objData.PaymentCount > 0) { hidNoOfPayment.Value = objData.PaymentCount.ToString(); GeneratePaymentTable(Convert.ToInt32(objData.PaymentCount)); } FillPaymentData(objData.ID); } } catch (Exception ex) { } } protected void GeneratePaymentTable(int createRows) { int rows = createRows; rows = rows * 1; int Columns = 2; int label = 1; for (int i = 0; i < rows; i++) { TableRow row = new TableRow(); for (int j = 0; j < Columns; j++) { TableCell cell = new TableCell(); if (j == 0) { cell.Width = new Unit(25, UnitType.Percentage); Label lbl = new Label(); lbl.ID = "PaymentLabel " + i; lbl.Text = "Payment " + label; lbl.Width = new Unit(100, UnitType.Percentage); lbl.Attributes.Add("runat", "server"); lbl.Attributes.Add("class", "col-sm-4 col-lg-3 control-label dynamicLabelFont"); cell.Controls.Add(lbl); } else if (j != 0) { TextBox txtPayment = new TextBox(); txtPayment.ID = "PaymentTextBox_" + i + "Col_" + j; txtPayment.Attributes.Add("runat", "server"); txtPayment.Attributes.Add("style", "border-radius:4px"); txtPayment.TextMode = TextBoxMode.Number; txtPayment.Attributes.Add("IncrementSettings-InterceptMouseWheel", "false"); txtPayment.Attributes.Add("NumberFormat-DecimalDigits", "2"); txtPayment.TextChanged += this.TextBox_TextChanged; txtPayment.AutoPostBack = true; txtPayment.Attributes.Remove("width"); cell.Controls.Add(txtPayment); } row.Cells.Add(cell); } label = label + 1; tblPayment.Rows.Add(row); } isPaymentTableCreated = true; } protected void FillPaymentData(long employeeId) { using (TestEntities entity = new TestEntities()) { Tbl_Employee employeeTBL = entity.Tbl_Employee.Where(a => a.ID == employeeId).FirstOrDefault(); if (employeeTBL != null && employeeTBL.PaymentCount != null) { List<Tbl_ReceivePayment> objListReceivePayments = entity.Tbl_ReceivePayment.Where(o => o.Employee_Id == employeeTBL.ID).ToList(); if (objListReceivePayments != null && objListReceivePayments.Count > 0) { foreach (TableRow row in tblPayment.Rows) { int rowIndex = tblPayment.Rows.GetRowIndex(row); foreach (TableCell cell in row.Cells) { int cellIndex = row.Cells.GetCellIndex(cell); if (cellIndex != 0) { var paymentValue = objListReceivePayments.Where(a => a.Employee_Id == employeeTBL.ID && a.RowIndex == rowIndex && a.ColIndex == cellIndex).Select(a => a.Payment).FirstOrDefault(); var rnPayment = cell.FindControl("PaymentTextBox_" + rowIndex + "Col_" + cellIndex) as TextBox; if (rnPayment != null) rnPayment.Text = (paymentValue.ToString()); } } } } } txt_Total.Text = CalculateTotal().ToString(); } } protected void btnAddPayment_Click(object sender, EventArgs e) { if (isPaymentTableCreated == false) { if (Convert.ToInt32(hidNoOfPayment.Value) >= 1) { GeneratePaymentTable(Convert.ToInt32(hidNoOfPayment.Value)); } } } protected void btnSubmit_Click(object sender, EventArgs e) { SaveData(); } protected void TextBox_TextChanged(object sender, EventArgs e) { txt_Total.Text = CalculateTotal().ToString(); } private decimal CalculateTotal() { decimal totalPayment = 0; if (tblPayment.Rows.Count > 0) { foreach (TableRow row in tblPayment.Rows) { int rowIndex = tblPayment.Rows.GetRowIndex(row); foreach (TableCell cell in row.Cells) { int cellIndex = row.Cells.GetCellIndex(cell); if (cellIndex != 0) { var txt_Payment = cell.Controls[0] as TextBox; if (txt_Payment != null) { totalPayment = totalPayment + Convert.ToDecimal(txt_Payment.Text); } } } } } return totalPayment; } public void SaveData() { try { TestEntities objTestEntity = new TestEntities(); long employeeId = Convert.ToInt64(lblEmployeeId.Text); Tbl_Employee employeeTbl = objTestEntity.Tbl_Employee.Where(a => a.ID == employeeId).FirstOrDefault(); if (employeeTbl == null) { employeeTbl = new Tbl_Employee(); } employeeTbl.FirstName = txtFirstName.Text; employeeTbl.LastName = txtLastName.Text; employeeTbl.State = txtState.Text; employeeTbl.City = txtCity.Text; employeeTbl.Address = txtAddress.Text; employeeTbl.PaymentCount = Convert.ToInt32(hidNoOfPayment.Value); employeeTbl.Total_Payment = CalculateTotal(); if (employeeTbl.ID > 0) { objTestEntity.Entry(employeeTbl).State = System.Data.Entity.EntityState.Modified; } else { objTestEntity.Tbl_Employee.Add(employeeTbl); } objTestEntity.SaveChanges(); if (!string.IsNullOrEmpty(hidNoOfPayment.Value)) { SavePaymentValues(employeeTbl.ID); } Response.Redirect("EmployeeList.aspx"); } catch (Exception ex) { } } protected void SavePaymentValues(int employeeId) { decimal totalPayments = 0; List<Tbl_ReceivePayment> list = new List<Tbl_ReceivePayment>(); foreach (TableRow row in tblPayment.Rows) { Tbl_ReceivePayment tblReceivePayment = null; int rowIndex = tblPayment.Rows.GetRowIndex(row); foreach (TableCell cell in row.Cells) { int cellIndex = row.Cells.GetCellIndex(cell); if (cellIndex != 0) { var txt_Payment = cell.Controls[0] as TextBox; if (txt_Payment != null) { tblReceivePayment = new Tbl_ReceivePayment(); tblReceivePayment.Employee_Id = employeeId; tblReceivePayment.RowIndex = rowIndex; tblReceivePayment.ColIndex = cellIndex; tblReceivePayment.Payment = Convert.ToDecimal(txt_Payment.Text); totalPayments = totalPayments + Convert.ToDecimal(txt_Payment.Text); list.Add(tblReceivePayment); } } } } using (TestEntities objentity = new TestEntities()) { try { List<Tbl_ReceivePayment> objListReceivedPayments = objentity.Tbl_ReceivePayment.Where(o => o.Employee_Id == employeeId).ToList(); if (objListReceivedPayments != null && objListReceivedPayments.Count > 0) { objentity.Tbl_ReceivePayment.RemoveRange(objListReceivedPayments); } if (list != null && list.Count > 0) { objentity.Tbl_ReceivePayment.AddRange(list); } objentity.SaveChanges(); } catch (Exception) { } } } } }

In above Employee.aspx page bind the data that is selected from the list page. In this page there are two buttons “Add Payment” and “Submit”. On Add Payment button click the dynamic textboxes are generate and add sequentially bottom of button. On dynamic generated textboxes enter the amount after entered your amount the total Amount is recalculate and show on the Total Amount Control. The dynamic generated textboxes position and values both are saving in Tbl_ReceivePayment. The Basic detail of employee on this page is FirstName, LastName, State, City, and Address. This Basic detail saves in Tbl_Employee.

EmployeeDetail

When click on Submit button then Basic details FirstName, LastName, State, City, Address, Total fields are save in Tbl_empoloyee table. When save this data in table it is generate one primary, auto increment Id. This Id is calling EmployeeId and this Id is use to saving Payment details in Tbl_ReceivePayment table. Because we will identify of payment details for particular employee. If you want to add one more payment then click on Add Payment button then one new dynamic textbox will generate. Add your payment in textbox and on text changed the total value is recalculate and show on Total textbox. On Submit button click data will be save and redirect on Employee List Page. On Employee List page you can see the basic detail with detail button. When you click on detail button redirect on detail page and you can see the Payment controls are showing as same sequence when you create new employee and added payment like Payment 1, 2, 3.

How to add dynamic textbox and save values to database in Asp.Net using C#.

This is main feature in this post to save control position also in table. So when you want to see payment details then you can see it sequentially.

If you like this post then posts your comment in below comment box. Please subscribe our site for new post.

Thanks,


1 comment:

Thank You,
If you have any doubt, Please let me know.
Please share this post so I will getting more advice/comment and i will make more efforts to post for readers bug/fix related.