Insert Data in Database Using GridView Control

Hello friends, we know many ways to insert data into a database.

In this article we will see how to insert data into the SQL Database and GridView using a GridView TextBox control. GridView is an important control for any database record displayed in any web and desktop application.

In this example use an update panel control and CSS to design the GridView.

Now here we will see step-by-step how to insert data into the database and also display the inserted record in the GridView.

Step 1

Create a table.

Example

  1. create table EmployeeDB  
  2. (  
  3. EmpID int primary key identity(1,1),  
  4. EmpName varchar(20),  
  5. EmpGender varchar(10),  
  6. EmpDOB date null,  
  7. EmpDepartment varchar(20)  

Create table

Step 2

Create a SQL procedure to insert data into the database.

  1. Create procedure sp_EmpDataInsert  
  2. @EmpName varchar(20),  
  3. @EmpGender varchar(10),  
  4. @EmpDOB date,  
  5. @EmpDepartment varchar(20)  
  6. as  
  7. begin  
  8. set nocount on;  
  9. insert into EmployeeDB  
  10. (EmpName,EmpGender,EmpDOB,EmpDepartment)  
  11. values  
  12. (@EmpName,@EmpGender,@EmpDOB,@EmpDepartment)  
  13. End 

record insert in database

Step 3

Now go to your project design (.aspx) page.

add new item

Add a page using Master page.

Master page

Step 4

Add a Script Manager as in the following:

  1. <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" EnablePageMethods="true" >  
  2. </asp:ScriptManager> 

Step 5

Add an Update panel for the currently inserted record as in the following:

  1. <asp:UpdatePanel runat="server" UpdateMode="Always" >  
  2. </asp:UpdatePanel> 

Step 6

Add a GridView control inside the Update panel as in the following:

  1. <asp:UpdatePanel runat="server" UpdateMode="Always"  >  
  2. <ContentTemplate>  
  3. <asp:GridView runat="server" ID="GridEmpData"  
  4.                  CssClass="Grid"   
  5.                  AutoGenerateColumns="false"   
  6.                  ShowFooter="true" >  
  7. </asp:GridView>  
  8. </ContentTemplate>  
  9.   
  10. </asp:UpdatePanel> 

Step 7

Add a CSS Style for the GridView Design as in the following:

  1. <style>  
  2.         body { font-size:65% }  
  3.  
  4.         #Employee {  
  5.             font:11px Times New Roman;   
  6.             width:auto;  
  7.             display:block;  
  8.             padding:10px 0 0 0;  
  9.         }  
  10.   
  11.         .text {  
  12.             width:auto;  
  13.             padding:2px 4px;  
  14.             font:inherit;  
  15.             font-weight:bold;  
  16.             text-align:left;  
  17.             border:solid 2px #BFBFBF;  
  18.             background:yellow;  
  19.             text-transform:uppercase;  
  20.         }  
  21.               
  22.         .Grid {  
  23.             width:100%;   
  24.             font:inherit;   
  25.             margin:5px 0 10px 0;   
  26.             background-color:#FFF;   
  27.             border:solid 2px #525252;  
  28.             text-transform:uppercase;  
  29.         }  
  30.         .Grid td {  
  31.             font:inherit;   
  32.             padding:2px;   
  33.             border:solid 1px #C1C1C1;   
  34.             color:#333;   
  35.             text-align:center;  
  36.         }  
  37.         .Grid th {  
  38.             padding:5px;   
  39.             color:blue;   
  40.             background:#424234 border-left:solid 3px #525233;   
  41.             font:inherit;  
  42.             font-weight:bold;  
  43.         }  
  44.               
  45.         .Gridbutton {  
  46.             cursor:pointer;   
  47.             text-align:center;   
  48.             color: white;   
  49.             font:inherit;  
  50.             background-color: blue;  
  51.             border:solid 1px #3079ED;   
  52.             -moz-border-radius:5px;   
  53.             -webkit-border-radius:5px;   
  54.             line-height:20px;  
  55.         }  
  56.     </style> 

Step 8

Finally, create your .aspx design page for the GridView as in the following:

  1. <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="GridDemo.aspx.cs" Inherits="Test_WebApplication.Form.WebForm1" %>  
  2. <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">  
  3. </asp:Content>  
  4. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">  
  5.   
  6. <div>  
  7.       
  8.     <%--GRIDVIEW CSS--%>  
  9.       <style>  
  10.         body { font-size:62.5% }  
  11.  
  12.         #Employee {  
  13.             font:11px Times New Roman;   
  14.             width:auto;  
  15.             display:block;  
  16.             padding:10px 0 0 0;  
  17.         }  
  18.   
  19.         .text {  
  20.             width:auto;  
  21.             padding:2px 4px;  
  22.             font:inherit;  
  23.             font-weight:bold;  
  24.             text-align:left;  
  25.             border:solid 2px #BFBFBF;  
  26.             background:yellow;  
  27.             text-transform:uppercase;  
  28.         }  
  29.               
  30.         .Grid {  
  31.             width:100%;   
  32.             font:inherit;   
  33.             margin:5px 0 10px 0;   
  34.             background-color:#FFF;   
  35.             border:solid 2px #525252;  
  36.             text-transform:uppercase;  
  37.         }  
  38.         .Grid td {  
  39.             font:inherit;   
  40.             padding:2px;   
  41.             border:solid 1px #C1C1C1;   
  42.             color:#333;   
  43.             text-align:center;  
  44.         }  
  45.         .Grid th {  
  46.             padding:5px;   
  47.             color:blue;   
  48.             background:#424234 border-left:solid 3px #525233;   
  49.             font:inherit;  
  50.             font-weight:bold;  
  51.         }  
  52.               
  53.         .Gridbutton {  
  54.             cursor:pointer;   
  55.             text-align:center;   
  56.             color: white;   
  57.             font:inherit;  
  58.             background-color: blue;  
  59.             border:solid 1px #3079ED;   
  60.             -moz-border-radius:5px;   
  61.             -webkit-border-radius:5px;   
  62.             line-height:20px;  
  63.         }  
  64.     </style>  
  65.   
  66. </div>  
  67.   
  68.     <%--- Add Script Manager ----%>  
  69.     <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" EnablePageMethods="true" >  
  70.     </asp:ScriptManager>  
  71.   
  72.     <div id="Employee">  
  73.         <asp:UpdatePanel runat="server" UpdateMode="Always"  >  
  74.             <ContentTemplate>  
  75.                 <asp:GridView runat="server" ID="GridEmpData"  
  76.                  CssClass="Grid"   
  77.                  AutoGenerateColumns="false"   
  78.                  ShowFooter="true" >  
  79.                  <Columns>  
  80.                     <asp:TemplateField HeaderText="Employee No.">  
  81.                         <ItemTemplate><%#Eval("EmpID")%></ItemTemplate>  
  82.                         <FooterTemplate><h4><i> INSERT NEW RECORD </i></h4></FooterTemplate>  
  83.                     </asp:TemplateField>  
  84.   
  85.                     <asp:TemplateField HeaderText="Employee Name">  
  86.                         <ItemTemplate><%#Eval("EmpName")%></ItemTemplate>  
  87.                         <FooterTemplate><asp:TextBox runat="server" ID="txtEmpName" CssClass="text"></asp:TextBox></FooterTemplate>  
  88.                     </asp:TemplateField>  
  89.                    
  90.                     <asp:TemplateField HeaderText="Gender">  
  91.                         <ItemTemplate><%#Eval("EmpGender")%></ItemTemplate>  
  92.                         <FooterTemplate><asp:TextBox runat="server" ID="txtEmpGender" CssClass="text"></asp:TextBox></FooterTemplate>  
  93.                     </asp:TemplateField>  
  94.   
  95.                     <asp:TemplateField HeaderText="Date of Birth">  
  96.                         <ItemTemplate><%#Eval("EmpDOB")%></ItemTemplate>  
  97.                         <FooterTemplate><asp:TextBox runat="server" ID="txtEmpDOB" CssClass="text"></asp:TextBox></FooterTemplate>  
  98.                     </asp:TemplateField>  
  99.   
  100.                     <asp:TemplateField HeaderText="Department">  
  101.                         <ItemTemplate><%#Eval("EmpDepartment")%></ItemTemplate>  
  102.                         <FooterTemplate><asp:TextBox runat="server" ID="txtEmpDpt" CssClass="text" ></asp:TextBox></FooterTemplate>  
  103.                     </asp:TemplateField>  
  104.   
  105.                     <asp:TemplateField>  
  106.                         <ItemTemplate></ItemTemplate>  
  107.                         <FooterTemplate><asp:Button runat="server" ID="btnSave" Text="SAVE NEW RECORD" CssClass="Gridbutton" CommandName="Footer" onclick="btnSave_Click" /></FooterTemplate>  
  108.                     </asp:TemplateField>  
  109.                  </Columns>  
  110.                    
  111.                  <EmptyDataTemplate>  
  112.                     <tr>  
  113.                         <th>Employee Name</th>  
  114.                         <th>Gender</th>  
  115.                         <th>Date of Birth</th>  
  116.                         <th>Department</th>  
  117.                         <th></th>  
  118.                     </tr  
  119.   
  120.                     <tr>  
  121.                         <td><asp:TextBox runat="server" ID="txtEmpName" CssClass="text"></asp:TextBox></td>  
  122.                         <td><asp:TextBox runat="server" ID="txtEmpGender" CssClass="text"></asp:TextBox></td>  
  123.                         <td><asp:TextBox runat="server" ID="txtEmpDOB" CssClass="text"></asp:TextBox></td>  
  124.                         <td><asp:TextBox runat="server" ID="txtEmpDpt" CssClass="text" ></asp:TextBox></td>  
  125.                         <td><asp:Button runat="server" ID="btnSave" Text="SAVE NEW RECORD" CssClass="Gridbutton" onclick="btnSave_Click" CommandName="EmptyDataTemplate" /></td>  
  126.                     </tr>  
  127.                                   
  128.                  </EmptyDataTemplate>  
  129.                   
  130.                 </asp:GridView>  
  131.             </ContentTemplate>  
  132.           
  133.         </asp:UpdatePanel>  
  134.       
  135.     </div>  
  136.       
  137.     <asp:Label runat="server" ID="lblmsg"></asp:Label>  
  138. </asp:Content> 

In this Design page add a GridView control and all database fields added in the GridView Template field and also in the last add a TextBox control for the record insert into the database and Button control inside the GridView Footer Template.

Also define an EmptyDataTemplate in the GridView design for the blank TextBox display and button control.

Step 9

Configure your database connection string in your project web.config file.

  1. <connectionStrings>  
  2.     <add name="connstr" connectionString="Data Source=RAKESH-PC;Initial Catalog=SqlServerTech;User ID=sa;Password=your SQL DB Password" providerName="System.Data.SqlClient"/>  
  3.   
  4.     <add name="Pratical_testConnectionString" connectionString="Data Source=RAKESH-PC;Initial Catalog=Pratical_test;User ID=sa" providerName="System.Data.SqlClient"/>  
  5.   </connectionStrings> 

Step 10

In the last step write the back-end code for the GridView data insert into the database and display on the grid view.

In the Page Design back-end write the following code.

First define the connection string as in the following:

  1. string conString = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString; 

After writing the code for the Grid View Data Bind in EmployeeDataGrid().

The following is the back-end code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Configuration;  
  8. using System.Data;  
  9. using System.Data.SqlClient;  
  10. namespace Test_WebApplication.Form  
  11. {  
  12.     public partial class WebForm1 : System.Web.UI.Page  
  13.     {  
  14.         string conString = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;  
  15.         protected void Page_Load(object sender, EventArgs e)  
  16.         {  
  17.             if (!Page.IsPostBack)  
  18.             {  
  19.                 EmployeeDataGrid();  
  20.             }  
  21.         }  
  22.         private void EmployeeDataGrid()  
  23.         {  
  24.             using (SqlConnection con = new SqlConnection(conString))  
  25.             {  
  26.                 using (SqlCommand cmd = new SqlCommand("select * from EmployeeDB"))  
  27.                 {  
  28.                     SqlDataAdapter dt = new SqlDataAdapter();  
  29.                     try  
  30.                     {  
  31.                         cmd.Connection = con;  
  32.                         con.Open();  
  33.                         dt.SelectCommand = cmd;  
  34.   
  35.                         DataTable dTable = new DataTable();  
  36.                         dt.Fill(dTable);  
  37.   
  38.                         GridEmpData.DataSource = dTable;  
  39.                         GridEmpData.DataBind();  
  40.                     }  
  41.                     catch(Exception)  
  42.                     {  
  43.                         lblmsg.Text = "record not found";  
  44.                     }  
  45.                 }  
  46.             }  
  47.         }  
  48.   
  49.         protected void btnSave_Click(object sender, EventArgs e)  
  50.         {          
  51.             Button btn = (Button)sender;  
  52.             GridViewRow GrdRow = (GridViewRow)btn.Parent.Parent;  
  53.   
  54.             TextBox txtEmpName = (TextBox)GrdRow.Cells[0].FindControl("txtEmpName");  
  55.             TextBox txtEmpGender = (TextBox)GrdRow.Cells[0].FindControl("txtEmpGender");  
  56.             TextBox txtEmpDOB = (TextBox)GrdRow.Cells[0].FindControl("txtEmpDOB");  
  57.             TextBox txtEmpDpt = (TextBox)GrdRow.Cells[0].FindControl("txtEmpDpt");  
  58.   
  59.   
  60.             using (SqlConnection con = new SqlConnection(conString))  
  61.             {  
  62.                  using (SqlCommand cmd = new SqlCommand())  
  63.                 {  
  64.                     cmd.CommandType = CommandType.StoredProcedure;  
  65.                     cmd.CommandText = "sp_EmpDataInsert";  
  66.   
  67.                     cmd.Connection = con;  
  68.                     con.Open();  
  69.   
  70.                     cmd.Parameters.AddWithValue("@EmpName",SqlDbType.VarChar).Value=txtEmpName.Text.Trim();  
  71.                     cmd.Parameters.AddWithValue("@EmpGender",SqlDbType.VarChar).Value=txtEmpGender.Text.Trim();  
  72.                     cmd.Parameters.AddWithValue("@EmpDOB",SqlDbType.Date).Value=txtEmpDOB.Text.Trim();  
  73.                     cmd.Parameters.AddWithValue("@EmpDepartment",SqlDbType.VarChar).Value=txtEmpDpt.Text;  
  74.   
  75.                     cmd.ExecuteNonQuery();  
  76.                 }  
  77.             }  
  78.             EmployeeDataGrid();  
  79.         }  
  80.   
  81.     }  

Finally to see your GridView control on your web form press F5 and run your aspx page.

Gridview control

And also, first check the database EmployeeDB table all the record fields are null using the SQL Select Query command.

  1. select * from EmployeeDB  
  2. --No Record inside table 

Insert record in textbox

Now insert a record into the TextBox and press the button to insert a TextBox record in the database and display a Grid View.

First fill in the TextBox and then press the button SAVE NEW RECORD.

fill textbox

Next see insert a record into the Grid view.

see inserted record

Grid view

And check also your inserted record in the database using the select Query command.

check also your inserted record

Finally check your inserted grid view record and that the database inserted records are the same. So the GridView example is complete. I hope you understand this example.

We are many more operation doing on TextBox data using GridView control as like data insert, update, delete. All types of these operations will be seen in a future article.