Sunday, August 2, 2015

Insert record into Database using Gridview in Asp.net

In this tutorial I am going to explain how to insert a new record into database using Gridview FooterTemplate in Asp.net

Description:

In this article I am going to use Geidview to insert new record into database. To implement this use the FooterTemplate inside the TemplateField. Put the textbox control inside FooterTemplate and set require field validation on textboxes.
Implementation:
Create a table Student_Detail 
Insert record into Database using Gridview in Asp.net


Drag and drop the gridview control from toolbox to Webform. Set the ShowFooter property of Gridview True.

HTML Markup of Gridview control:
<asp:GridView ID="GridView1" runat="server" Width="550px" AutoGenerateColumns="False" ShowFooter="True" AllowPaging="True" CellPadding="4" ForeColor="#333333" GridLines="None">
  <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    <Columns>
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:Label ID="lblname" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtname" runat="server" />
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Enter Name" ControlToValidate="txtname"></asp:RequiredFieldValidator>
            </FooterTemplate>
            <ItemStyle HorizontalAlign="Center" />
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Fee">
            <ItemTemplate>
               <asp:Label ID="lblfee" runat="server" Text='<%# Eval("Fee") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtfee" runat="server" />
                 <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Enter Fee" ControlToValidate="txtfee"></asp:RequiredFieldValidator>
            </FooterTemplate>
             <ItemStyle HorizontalAlign="Center" />
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Class">
            <ItemTemplate>
               <asp:Label ID="lblclass" runat="server" Text='<%# Eval("Class") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtclass" runat="server"></asp:TextBox>
                 <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Enter Class" ControlToValidate="txtclass"></asp:RequiredFieldValidator>
            </FooterTemplate>
             <ItemStyle HorizontalAlign="Center" />
        </asp:TemplateField>
           <asp:TemplateField HeaderText="Roll Number">
            <ItemTemplate>
                <asp:Label ID="lblrollno" runat="server" Text='<%# Eval("RollNo") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtrollno" runat="server"></asp:TextBox>
                 <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Enter Roll number" ControlToValidate="txtrollno"></asp:RequiredFieldValidator>
            </FooterTemplate>
                <ItemStyle HorizontalAlign="Center" />
        </asp:TemplateField>
            <asp:TemplateField>
            <ItemTemplate>
            </ItemTemplate>
            <FooterTemplate>
                <asp:Button ID="btninsert" runat="server" Text="Insert Record" CommandName="Insert" />
            </FooterTemplate>
                <ItemStyle VerticalAlign="Top" />
        </asp:TemplateField>
    </Columns>
                       <EditRowStyle BackColor="#999999" />
                       <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                       <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                       <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                       <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                       <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                       <SortedAscendingCellStyle BackColor="#E9E7E2" />
                       <SortedAscendingHeaderStyle BackColor="#506C8C" />
                       <SortedDescendingCellStyle BackColor="#FFFDF8" />
                       <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>

Add the Namespace to code file
C#:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Bind the Gridview
Write and
C#:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {     
        if (!IsPostBack)
        {
            BindGridview();
        }
    }
    public void BindGridview()
    {
        try
        {
            SqlDataAdapter adp = new SqlDataAdapter("Select * from Student_Detail", con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
         }
        catch(Exception ex)
        {

        }
    }

VB:
  Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindGridview()
        End If
    End Sub
    Public Sub BindGridview()
        Try
            Dim adp As New SqlDataAdapter("Select * from Student_Detail", con)
            Dim dt As New DataTable()
            adp.Fill(dt)
            GridView1.DataSource = dt
            GridView1.DataBind()
        Catch ex As Exception
        End Try
    End Sub

Pagination
C#:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindGridview();
    }

VB:
Protected Sub GridView1_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles GridView1.PageIndexChanging
        GridView1.PageIndex = e.NewPageIndex
        BindGridview()
    End Sub

Handel the RowCommand Event of gridview
C#:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Insert")
        {
            SqlCommand cmd = new SqlCommand("Insert into Student_Detail(Name,Fee,Class,RollNo) values(@name,@fee,@class,@rollno)", con);
            TextBox txtname = (TextBox)GridView1.FooterRow.FindControl("txtname");
            TextBox txtfee = (TextBox)GridView1.FooterRow.FindControl("txtfee");
            TextBox txtclass = (TextBox)GridView1.FooterRow.FindControl("txtclass");
            TextBox txtrollno = (TextBox)GridView1.FooterRow.FindControl("txtrollno");
            con.Open();
            cmd.Parameters.AddWithValue("@name", txtname.Text);
            cmd.Parameters.AddWithValue("@fee", txtfee.Text);
            cmd.Parameters.AddWithValue("@class", txtclass.Text);
            cmd.Parameters.AddWithValue("@rollno", txtrollno.Text);
            cmd.ExecuteNonQuery();
            con.Close();
            Response.Write("<script type=\"text/javascript\">alert('Record Insert Successfully!!!');</script>");
            BindGridview();
            txtname.Text = string.Empty;
            txtfee.Text = string.Empty;
            txtclass.Text = string.Empty;
            txtrollno.Text = string.Empty;
        }
    }

VB:
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GridView1.RowCommand
        If e.CommandName = "Insert" Then
            Dim cmd As New SqlCommand("Insert into Student_Detail(Name,Fee,Class,RollNo) values(@name,@fee,@class,@rollno)", con)
            Dim txtname As TextBox = DirectCast(GridView1.FooterRow.FindControl("txtname"), TextBox)
            Dim txtfee As TextBox = DirectCast(GridView1.FooterRow.FindControl("txtfee"), TextBox)
            Dim txtclass As TextBox = DirectCast(GridView1.FooterRow.FindControl("txtclass"), TextBox)
            Dim txtrollno As TextBox = DirectCast(GridView1.FooterRow.FindControl("txtrollno"), TextBox)
            con.Open()
            cmd.Parameters.AddWithValue("@name", txtname.Text)
            cmd.Parameters.AddWithValue("@fee", txtfee.Text)
            cmd.Parameters.AddWithValue("@class", txtclass.Text)
            cmd.Parameters.AddWithValue("@rollno", txtrollno.Text)
            cmd.ExecuteNonQuery()
            con.Close()
            Response.Write("<script type=""text/javascript"">alert('Insert Record Successfully!!!');</script>")
            txtname.Text = String.Empty
            txtfee.Text = String.Empty
            txtclass.Text = String.Empty
            txtrollno.Text = String.Empty
        End If
    End Sub

Build, run the project.

Result:
Insert record into Database using Gridview in Asp.net


     In this article we have learn how to Insert record into database table using Gridview in asp.net (C#, VB). I hope you enjoyed this article.

No comments:

Post a Comment