Wednesday, December 23, 2015

Dynamically add remove rows in table in ASP.NET using javascript

In this article I am going to explain how to add and delete row of Table in ASP. net c# using JavaScript and use their value in c#.

Add and delete row in table JavaScript

<script type="text/javascript">
        function AddNewRecord() {
            var grd = document.getElementById("gvEmp");
            var lengthgrd = grd.rows.length - 1;
        
              //validation check
            if (lengthgrd >= 1) {
 
                var Name = grd.rows[lengthgrd].cells[0].getElementsByTagName('input')[0].value;
                if (Name.trim() == "") {
                    alert("Please Fill Name.");
                    return false;
                }
              
                var Gender = grd.rows[lengthgrd].cells[2].getElementsByTagName('select')[0].value;
                if (Gender.trim() == "Select Gender") {
                    alert("Please Select Gender.");
                    return false;
                }
            }
            var tbod = grd.rows[0].parentNode;
            var newRow = grd.rows[grd.rows.length - 1].cloneNode(true);
            tbod.appendChild(newRow);
            addvalue();//new row add with empty value
        }
 
 
        function addvalue() {
            var grd = document.getElementById("gvEmp");
            var no = grd.rows.length - 1
            grd.rows[no].cells[0].getElementsByTagName('input')[0].value = "";
            grd.rows[no].cells[1].getElementsByTagName('input')[0].value = "";
        }
 
 
        //delete row
        function deleteRow(row) {
            var i = row.parentNode.parentNode.rowIndex;
            var x = document.getElementById("gvEmp");
            var xx = x.rows.length - 1;
 
            if (xx != 1) {
                document.getElementById("gvEmp").deleteRow(i);
            }
            if (xx == 1) {
                x.rows[1].cells[0].getElementsByTagName('input')[0].value = "";
                x.rows[1].cells[1].getElementsByTagName('input')[0].value = "";
                x.rows[1].cells[2].getElementsByTagName('select')[0].value = "Select Gender";
            }
        }
    </script> 

aspx code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript">
        function AddNewRecord() {
            var grd = document.getElementById("gvEmp");
            var lengthgrd = grd.rows.length - 1;
        
              //validation check
            if (lengthgrd >= 1) {
 
                var Name = grd.rows[lengthgrd].cells[0].getElementsByTagName('input')[0].value;
                if (Name.trim() == "") {
                    alert("Please Fill Name.");
                    return false;
                }
              
                var Gender = grd.rows[lengthgrd].cells[2].getElementsByTagName('select')[0].value;
                if (Gender.trim() == "Select Gender") {
                    alert("Please Select Gender.");
                    return false;
                }
            }
            var tbod = grd.rows[0].parentNode;
            var newRow = grd.rows[grd.rows.length - 1].cloneNode(true);
            tbod.appendChild(newRow);
            addvalue();//new row add with empty value
        }
 
 
        function addvalue() {
            var grd = document.getElementById("gvEmp");
            var no = grd.rows.length - 1
            grd.rows[no].cells[0].getElementsByTagName('input')[0].value = "";
            grd.rows[no].cells[1].getElementsByTagName('input')[0].value = "";
        }
 
 
        //delete row
        function deleteRow(row) {
            var i = row.parentNode.parentNode.rowIndex;
            var x = document.getElementById("gvEmp");
            var xx = x.rows.length - 1;
 
            if (xx != 1) {
                document.getElementById("gvEmp").deleteRow(i);
            }
            if (xx == 1) {
                x.rows[1].cells[0].getElementsByTagName('input')[0].value = "";
                x.rows[1].cells[1].getElementsByTagName('input')[0].value = "";
                x.rows[1].cells[2].getElementsByTagName('select')[0].value = "Select Gender";
            }
        }
 
 
        //assign value into textbox
 
        function AssignGender(row) {
 
            var rowvalue = $(row).closest('tr').index();
            var grd = document.getElementById("gvEmp");
            var Gender = grd.rows[rowvalue].cells[2].getElementsByTagName('select')[0].value;
            document.getElementById("txtGender").value = Gender;
           
        }
 
    </script>
  
</head>
<body>
    <form id="form1" runat="server">
  <fieldset style="border:1px solid #cccccc; position:relative;">
<legend style="font-size:14px; font-weight:bold; color:#395b77; margin-left:4px; padding:0px 5px;">Employee Detail</legend>
 
 
<input type="button" id="Add Employee" value="Add More Row" onclick="AddNewRecord()" class="btnaddmor" />
 
<table id="gvEmp" border="1" runat="server">
 
<tr>
<td class="hed">Name</td>
<td class="hed">Age</td>
<td class="hed">Gender</td>
<td class="hed">Delete</td>
</tr>
 
<tr>
<td>
<asp:TextBox ID="txtName" runat="server" MaxLength="50" onkeypress="return ValidateText(event)" onpaste="return false" >
</asp:TextBox>
</td>
 
<td>
<asp:TextBox ID="txtAge" runat="server" MaxLength="2" ></asp:TextBox>
</td>
 
 
 
<td align="center">
<asp:DropDownList ID="ddlGender" runat="server" onchange="AssignGender(this)">
<asp:ListItem>Select Gender</asp:ListItem>
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="txtGender" runat="server" style="display:none;"></asp:TextBox>
</td>
 
 
<td align="center"><input type="button" id="delbutton" value="Delete" onclick="deleteRow(this)" class="btndel" /></td>
</tr>
</table>
 
<asp:Button ID="btnGettableValue" Text="Get Value" runat="server"
          onclick="btnGettableValue_Click" />
      <asp:GridView ID="GridView1" runat="server">
      </asp:GridView>
</fieldset>
    </form>
</body>
</html>

cs code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void btnGettableValue_Click(object sender, EventArgs e)
    {
 
        // get all aspx table value in c#
        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Age");
        dt.Columns.Add("Gender");
        int GridRow = gvEmp.Rows.Count;
        if (GridRow > 0)
        {
            TextBox Name = (TextBox)gvEmp.Rows[0].FindControl("txtName");
            TextBox Age = (TextBox)gvEmp.Rows[0].FindControl("txtAge");
            TextBox Gender = (TextBox)gvEmp.Rows[0].FindControl("txtGender");
            DropDownList dGender = (DropDownList)gvEmp.Rows[0].FindControl("ddlGender");
 
 
            string[] SplitName = Name.Text.Split(',');
            string[] SplitAge = Age.Text.Split(',');
            string[] SplitGender = Gender.Text.Split(',');
 
            for (int iCount = 0; iCount < SplitName.Length; iCount++)
            {
                if (!string.IsNullOrEmpty(SplitName[iCount].Trim()))
                {
 
                    int updatevalue = iCount;
                    ++updatevalue;
                    DataRow rr = dt.NewRow();
                    rr["Name"] = SplitName[iCount];
                    rr["Age"] = SplitAge[iCount];
                    rr["Gender"] = SplitGender[iCount];
                    dt.Rows.Add(rr);
                }
            }
 
 
            //empty table rows
            Name.Text = "";
            Age.Text = "";
            Gender.Text = "";
            dGender.SelectedIndex = 0;
        }
 
 
        // show table value in gridview
        GridView1.DataSource = dt;
        GridView1.DataBind();
 
    }
}

No comments:

Post a Comment