Insert data in GridView without using a database in ASP.NET

Codingvila
0

Introduction


This article gives an explanation about how to insert data in GridView without using a database in asp.net using c# and vb.net and explains how to add new programmatically into GridView in asp.net with example. Here I will also explain what is ViewState in asp.net as well as the use of ViewState in asp.net webforms.

In my previous article, I explained how to export GridView in excel using jquery in asp.net web forms, how to find the last date of any month in SQL Server, how to get selected row cell value from the GridView in asp.net webforms as well as explains get distinct records from Datatable using LINQ c#.
Insert data in GridView without using a database in ASP.NET

While we working with any web application sometimes we get such a requirement where we need to add the data into GridView and not save directly to the database based on the input fields. Today I got the same requirement where I need to insert data into GridView and then finally all the data from the GridView needs to save into database in a single click, So, In this article, I'll explain how to insert data into GridView without using a database and in my next article, I will explain how to save data from GridView to database in single click.

So, let's start with a simple example for a demonstration of how to insert data into GridView without using a database in asp.net, but before that, we will clear our actual requirement that I have described below.

Requirement


1) What is ViewState?
2) Explain How to insert data into GridView without using Database in asp.net with example.

Implementation

What is ViewState?


ViewState is a page-level state management technique. it is used to preserve the value of the controls or page between the round trips. if we save any value of a control or anything else in the ViewState variable then we can access those values throughout the page whenever it required.

So, Let's start with the implementation of the example for insert data/row into GridView in asp.net. Here we will take an example of the employee management system and will design a web form to gather employee details such as employee code, first name, last name, company name, department, designation and etc.

So, First, we will create a simple empty asp.net webform application and add one aspx web form.

Now, we have to design a form where we will get input from the user for employee code, first name, last name, company name, department, designation and etc with help pf textbox and we will also create a GridView for employee details, So, first we will add required scripts and CSS before end <head> tag as shown as below.
<head runat="server">
    <title></title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
Now, you have to write the following HTML code before the end <body> tag.
<body>
    <form id="form1" runat="server">
 
        <div class="container">
           <div class="form-row">
               <br />
                <div class="form-group col-md-12">
                   <center><h2>Employee Details</h2></center>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group col-md-12">
                    <label for="inputCity">Company Name</label>
                    <asp:TextBox ID="txtCompany" runat="server" CssClass="form-control" placeholder="Company Name" aria-label="Company"></asp:TextBox>
                </div>
                 <div class="form-group col-md-4">
                    <label for="inputCity">EmployeeCode</label>
                    <asp:TextBox ID="txtEmployeeCode" runat="server" CssClass="form-control" placeholder="Employee Code" aria-label="EmployeeCode"></asp:TextBox>
                </div>
                <div class="form-group col-md-4">
                    <label for="inputCity">FirstName</label>
                    <asp:TextBox ID="txtFirstName" runat="server" CssClass="form-control" placeholder="First Name" aria-label="FirstName"></asp:TextBox>
                </div>
                <div class="form-group col-md-4">
                    <label for="inputCity">LastName</label>
                    <asp:TextBox ID="txtLastName" runat="server" CssClass="form-control" placeholder="Last Name" aria-label="LastName"></asp:TextBox>
                </div>
                <div class="form-group col-md-4">
                    <label for="inputCity">Department</label>
                    <asp:TextBox ID="txtDepartment" runat="server" CssClass="form-control" placeholder="Department" aria-label="Department"></asp:TextBox>
                </div>
                <div class="form-group col-md-4">
                    <label for="inputCity">Designation</label>
                    <asp:TextBox ID="txtDesignation" runat="server" CssClass="form-control" placeholder="Designation" aria-label="Designation"></asp:TextBox>
                </div>
                <div class="form-group col-md-4">
                    <label for="inputCity">Blood Group</label>
                    <asp:TextBox ID="txtBloodgroup" runat="server" CssClass="form-control" placeholder="Blood Group" aria-label="BloodGroup"></asp:TextBox>
                </div>
                <div class="form-group col-md-2">
                    <asp:Button ID="btnInsert" runat="server" CssClass="btn btn-success" Text="Insert Record" OnClick="btnInsert_Click" />
                </div>
                <div class="form-group col-md-12">
                    <div class="panel panel-default ">
                        <div class="panel-heading">Employee Grid</div>
                        <div class="panel-body">
                            <asp:GridView ID="grdEmployees" runat="server" CssClass="table table-bordered active active" AutoGenerateColumns="false" EmptyDataText="No records has been found.">
                                 <Columns>
                                     <asp:BoundField DataField="Company" HeaderText="Company" ItemStyle-Width="120" />
                                     <asp:BoundField DataField="EmployeeCode" HeaderText="EmployeeCode" ItemStyle-Width="120" />
                                     <asp:BoundField DataField="FirstName" HeaderText="FirstName" ItemStyle-Width="120" />
                                     <asp:BoundField DataField="LastName" HeaderText="LastName" ItemStyle-Width="120" />
                                     <asp:BoundField DataField="Department" HeaderText="Department" ItemStyle-Width="150" />
                                     <asp:BoundField DataField="Designation" HeaderText="Designation" ItemStyle-Width="120" />
                                     <asp:BoundField DataField="BloodGroup" HeaderText="BloodGroup" ItemStyle-Width="70" />
                                 </Columns>
                            </asp:GridView>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</body>
Now we have to write the following code in the code behind, and as you can see in the code below,  

C#

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class CS : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[7] { new DataColumn("Company"), new DataColumn("EmployeeCode"), new DataColumn("FirstName"), new DataColumn("LastName"), new DataColumn("Department"), new DataColumn("Designation"), new DataColumn("BloodGroup") });
            ViewState["Employees"] = dt;
            this.BindEmployeeGrid();
        }
    }
    protected void BindEmployeeGrid()
    {
        try
        {
            grdEmployees.DataSource = (DataTable)ViewState["Employees"];
            grdEmployees.DataBind();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    protected void InsertRow()
    {
        try
        {
            DataTable dt = (DataTable)ViewState["Employees"];
            dt.Rows.Add(txtCompany.Text.Trim(), txtEmployeeCode.Text.Trim(), txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtDepartment.Text.Trim(), txtDesignation.Text.Trim(), txtBloodgroup.Text.Trim());
            ViewState["Employees"] = dt;
            this.BindEmployeeGrid();
            ClearFields();
        }
        catch (Exception ex)
        {
 
            throw;
        }
    }
 
    protected void ClearFields()
    {
        try
        {
            txtCompany.Text = string.Empty;
            txtEmployeeCode.Text = string.Empty;
            txtFirstName.Text = string.Empty;
            txtLastName.Text = string.Empty;
            txtDepartment.Text = string.Empty;
            txtDesignation.Text = string.Empty;
            txtBloodgroup.Text = string.Empty;
        }
        catch (Exception ex)
        {
 
            throw ex;
        }
    }
    protected void btnInsert_Click(object sender, EventArgs e)
    {
        try
        {
            InsertRow();
        }
        catch (Exception ex)
        {
 
            throw ex;
        }
    }
}

Output

Insert data in GridView without using a database

Summary


In this article, we learned how to insert data into GridView without using GridView as well as the basics of ViewState.

Post a Comment

0 Comments

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

Sometimes I not able to give detailed level explanation for your questions or comments, if you want detailed explanation, your can mansion your contact email id along with your question or you can do select given checkbox "Notify me" the time of write comment. So we can drop mail to you.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

Post a Comment
To Top