Add Values from Textboxes to GridView using jQuery

← PrevNext →

We know how to extract data from a data source and bind it with a GridView control using SqlDataSource. In-fact there is numerous other ways to extract and bind data in Asp.Net using code-behind procedures. However, in this article we will see how to add values from textboxes to a GridView control using jQuery.

This article is for beginners, who wish to learn some basic technique on data exchange between few textboxes and the mighty GridView control.

The technique is very simple yet useful. Simply imagine you have few textbox controls and you would like to get the values from these textboxes and fill in the columns and simultaneously add new rows with data to the GridView.

Add Textbox value to GridView

The above image explains it all. Let us now see how our example works. I'll first add a GridView control with three textboxes on my web page.

The Markup
<!DOCTYPE html>
<html>
<head>
    <title>Textbox to GridView using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

    <style>
        div {
            width:500px; 
        }
        .grid {
            width:100%; 
            font:inherit; 
            background-color:#FFF; 
            border:solid 1px #525252;
        }
        .grid td {
            padding:2px; 
            border:solid 1px #C1C1C1; 
            color:#333; 
            text-align:center; 
            text-transform:uppercase;
        }
        .grid th  {
            padding:3px; 
            color:#FFF; 
            background:#424242 url(grd.png) repeat-x top; 
            border-left:solid 1px #525252; 
            text-align:center; 
            text-transform:uppercase;
        }
        ul {
            padding:0; 
            margin:2px 5px; 
            list-style:none; 
            border:0; 
            float:left; 
            width:70%;
        }
        li {
            width:50%; 
            float:left; 
            display:inline-block; 
        }
    </style>    
</head>
<body>
    <form runat="server">
    <div>
        <%--MY GRIDVIEW CONTROL--%>
        <asp:GridView ID="grdBooks"
            runat="server" 
            AutoGenerateColumns="False" 
            DataKeyNames="EmpID" 
            DataSourceID="SqlDataSource1" 
            CssClass="grid" 
            GridLines="None">

            <Columns>
                <asp:BoundField DataField="EmpID" HeaderText="EmpID" 
                    ReadOnly="True" SortExpression="EmpID" />
                <asp:BoundField DataField="EmpName" HeaderText="EmpName" 
                    SortExpression="EmpName" />
                <asp:BoundField DataField="Designation" HeaderText="Designation" 
                    SortExpression="Designation" />
                <asp:BoundField DataField="Department" HeaderText="Department" 
                    SortExpression="Department" />
            </Columns>
        </asp:GridView>

        <%--POPULATE DATA TO THE GRIDVIEW USING SqlDataSource--%>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:ENCODEDNAConnectionString %>" 
            SelectCommand="SELECT [EmpID], [EmpName], [Designation], [Department] FROM [Employee]">
        </asp:SqlDataSource> 
        <br />

        <%--FEW TEXTBOXES WITH A BUTTON--%>
        <div id="divContainer">
            <ul>
                <li><label>Employee Name: </label></li>
                <li><input type="text" id="tbEmp" /></li>
            </ul>
            <ul>
                <li><label>Designation: </label></li>
                <li><input type="text" id="tbDesig" /></li>
            </ul>
            <ul>
                <li><label>Department: </label></li>
                <li><input type="text" id="tbDep" /></li>
            </ul>
            <ul>
                <li></li>
                <li>
                    <input type="button" id="btAdd" value="Add to Grid" />
                </li>
            </ul>
        </div>
    </div>
    </form>
</body>

Inside the <body> section, I have added a GridView control, followed by three labels and textboxes. Using SqlDataSource, I have populated the Grid with few rows of data. This is easiest way to initialize a GridView control and add few columns and rows to it.

The Script
<script>
    $('#btAdd').click(function () {
        var rowCount;
        rowCount = $('#grdEmployee tr').length;         // GET ROW COUNT.

        // ADD TEXTBOX VALUES TO THE GRIDVIEW.
        if ($('#tbEmp').val() != '' && $('#grdEmployee tr').length > 1) {
            $('#grdEmployee tr:last').after('<tr><td>' + rowCount + '</td>' +
                '<td>' + $('#tbEmp').val() + '</td>' +
                '<td>' + $('#tbDesig').val() + '</td>' +
                '<td>' + $('#tbDep').val() + '</td>' + '</tr>');

            // CLEAR ALL TEXTBOXES.
            $('#divContainer').find('input:text').each(function () {
                    $('input:text[id=' + $(this).attr('id') + ']').val('');
                }
            );
        }
        else alert('Invalid!');
    });
</script>
</html>

The above script is executed on button click event. The script has three important sections.

In the first part, I'll get the total row count of the GridView. It provides me the last unique ID of the employee, listed in the Grid. Later, when necessary, I can save the data in a database table using the unique ID. To get the row count I have used jQuery .length() method

Second, I'll extract the values from each textbox and add the values to the GridView. In addition, it creates a new row and adds it to the Grid. Remember, every time you click the button, it will add a new row.

See, how I have used the <table> element features in my jQuery script. This is because, the GridView produces a <table> like structure when rendered on the browser. Check this article to understand this better.

Finally, I'll clear all the textboxes at once using a jQuery procedure.

$('#divContainer').find('input:text').each(function () {
        $('input:text[id=' + $(this).attr('id') + ']').val('');
    }
);

All the textboxes are inside a <div> element (a container). Using jQuery .find() and .each() method, I can quickly clear the input boxes, once values are added to the Grid.

Conclusion

Simple and yet useful, this article just showed you how to extract values from textboxes and add it to a GridView control. We also saw how to get the total rows count of a GridView control and how we can clear all the input fields with the click of a single button.

← PreviousNext →