Latest

random

ASP.Net GridView C# Tutorial

ASP.Net Gridview Example in C#

ASP.Net GridView control displays the values of a data source in a table format where each column represents a field and each row represents a record. Aspx gridview enables you to select, sort, and edit these items. This example demonstrates you how to implement Insert, Edit, Update, Delete, Paging and Sorting functions in ASP.NET GridView control.


|- Related article Gridview Css Styles Example
After seeing many posts in asp.net forums about this powerful asp.net datagrid, so this sample provides a complete sample for showing how to implement these basic functions of this control. Find the below gridview edit update delete in asp net example source code :-

Namespace:   System.Web.UI.WebControls
Assembly:  System.Web (in System.Web.dll)
asp net gridview sample c#,asp.net grid view c#,asp.net gridview example in c#,asp.net gridview example using c#,grid view example in asp.net using c#,grid view example in asp.net with c#,gridview example in asp.net c#
asp.net gridview example using c#
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Insert Update Delete in Gridview in ASP .Net with C# Code Project</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="gvPerson" runat="server" AutoGenerateColumns="False" CellPadding="3"
                OnPageIndexChanging="gvPerson_PageIndexChanging"
                OnRowCancelingEdit="gvPerson_RowCancelingEdit"
                OnRowDataBound="gvPerson_RowDataBound" OnRowDeleting="gvPerson_RowDeleting"
                OnRowEditing="gvPerson_RowEditing" OnRowUpdating="gvPerson_RowUpdating"
                OnSorting="gvPerson_Sorting" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px">
                <RowStyle ForeColor="#000066" />
                <Columns>
                    <asp:CommandField ShowEditButton="True" />
                    <asp:CommandField ShowDeleteButton="True" />
                    <asp:BoundField DataField="PersonID" HeaderText="Id" ReadOnly="True"
                        SortExpression="PersonID" />

                    <asp:TemplateField HeaderText="FirstName" SortExpression="FirstName">
                        <EditItemTemplate>
                            <asp:TextBox ID="tbFirstName" runat="server" Text='<%# Bind("FirstName") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="LastName" SortExpression="LastName">
                        <EditItemTemplate>
                            <asp:TextBox ID="tbLastName" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <FooterStyle BackColor="White" ForeColor="#000066" />
                <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
                <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
                <SortedAscendingCellStyle BackColor="#F1F1F1" />
                <SortedAscendingHeaderStyle BackColor="#007DBB" />
                <SortedDescendingCellStyle BackColor="#CAC9C9" />
                <SortedDescendingHeaderStyle BackColor="#00547E" />
            </asp:GridView>

            <br />
            <asp:LinkButton ID="lbtnAdd" runat="server" OnClick="lbtnAdd_Click">AddNew</asp:LinkButton>
            <br />
            <br />
            <asp:Panel ID="pnlAdd" runat="server" Visible="False">
                First name:
            <asp:TextBox ID="tbFirstName" runat="server"></asp:TextBox>
                <br />
                <br />
                Last name:
            <asp:TextBox ID="tbLastName" runat="server"></asp:TextBox>
                <br />
                <br />

                <asp:LinkButton ID="lbtnSubmit" runat="server" OnClick="lbtnSubmit_Click">Submit</asp:LinkButton>
                &nbsp;&nbsp;&nbsp;
            <asp:LinkButton ID="lbtnCancel" runat="server" OnClick="lbtnCancel_Click">Cancel</asp:LinkButton>

            </asp:Panel>
        </div>
    </form>
</body>
</html>

Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // The Page is accessed for the first time.
        if (!IsPostBack)
        {
            // Initialize the DataTable and store it in ViewState.
            InitializeDataSource();

            // Enable the GridView paging option and specify the page size.
            gvPerson.AllowPaging = true;
            gvPerson.PageSize = 5;

            // Enable the GridView sorting option.
            gvPerson.AllowSorting = true;

            // Initialize the sorting expression.
            ViewState["SortExpression"] = "PersonID ASC";

            // Populate the GridView.
            BindGridView();
        }
    }

    // Initialize the DataTable.
    private void InitializeDataSource()
    {
        // Create a DataTable object named dtPerson.
        DataTable dtPerson = new DataTable();

        // Add four columns to the DataTable.
        dtPerson.Columns.Add("PersonID");
        dtPerson.Columns.Add("FirstName");
        dtPerson.Columns.Add("LastName");
       

        // Specify PersonID column as an auto increment column
        // and set the starting value and increment.
        dtPerson.Columns["PersonID"].AutoIncrement = true;
        dtPerson.Columns["PersonID"].AutoIncrementSeed = 1;
        dtPerson.Columns["PersonID"].AutoIncrementStep = 1;

        // Set PersonID column as the primary key.
        DataColumn[] dcKeys = new DataColumn[1];
        dcKeys[0] = dtPerson.Columns["PersonID"];
        dtPerson.PrimaryKey = dcKeys;

        // Add new rows into the DataTable.
        dtPerson.Rows.Add(null, "Ravi", "Kumar");
        dtPerson.Rows.Add(null, "Sachin", "Kumar");
        dtPerson.Rows.Add(null, "Nitin", "Kumar");
        dtPerson.Rows.Add(null, "Rajiv", "Gupta");
        dtPerson.Rows.Add(null, "Manish", "Singh");
        dtPerson.Rows.Add(null, "Amit", "Singh");
        dtPerson.Rows.Add(null, "Ajay", "Kumar");

        // Store the DataTable in ViewState.
        ViewState["dtPerson"] = dtPerson;
    }

    private void BindGridView()
    {
        if (ViewState["dtPerson"] != null)
        {
            // Get the DataTable from ViewState.
            DataTable dtPerson = (DataTable)ViewState["dtPerson"];

            // Convert the DataTable to DataView.
            DataView dvPerson = new DataView(dtPerson);

            // Set the sort column and sort order.
            dvPerson.Sort = ViewState["SortExpression"].ToString();

            // Bind the GridView control.
            gvPerson.DataSource = dvPerson;
            gvPerson.DataBind();
        }
    }

    // GridView.RowDataBound Event
    protected void gvPerson_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        // Make sure the current GridViewRow is a data row.
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // Make sure the current GridViewRow is either
            // in the normal state or an alternate row.
            if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
            {
                // Add client-side confirmation when deleting.
                ((LinkButton)e.Row.Cells[1].Controls[0]).Attributes["onclick"] = "if(!confirm('Are you certain you want to delete this person ?')) return false;";
            }
        }
    }

    // GridView.PageIndexChanging Event
    protected void gvPerson_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        // Set the index of the new display page. 
        gvPerson.PageIndex = e.NewPageIndex;

        // Rebind the GridView control to
        // show data in the new page.
        BindGridView();
    }

    // GridView.RowEditing Event
    protected void gvPerson_RowEditing(object sender, GridViewEditEventArgs e)
    {
        // Make the GridView control into edit mode
        // for the selected row.
        gvPerson.EditIndex = e.NewEditIndex;

        // Rebind the GridView control to show data in edit mode.
        BindGridView();

        // Hide the Add button.
        lbtnAdd.Visible = false;
    }

    // GridView.RowCancelingEdit Event
    protected void gvPerson_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        // Exit edit mode.
        gvPerson.EditIndex = -1;

        // Rebind the GridView control to show data in view mode.
        BindGridView();

        // Show the Add button.
        lbtnAdd.Visible = true;
    }

    // GridView.RowUpdating Event
    protected void gvPerson_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        if (ViewState["dtPerson"] != null)
        {
            // Get the DataTable from ViewState.
            DataTable dtPerson = (DataTable)ViewState["dtPerson"];

            // Get the PersonID of the selected row.
            string strPersonId = gvPerson.Rows[e.RowIndex].Cells[2].Text;

            // Find the row in DateTable.
            DataRow drPerson = dtPerson.Rows.Find(strPersonId);

            // Retrieve edited values and updating respective items.
            drPerson["FirstName"] = ((TextBox)gvPerson.Rows[e.RowIndex].FindControl("tbFirstName")).Text;
            drPerson["LastName"] = ((TextBox)gvPerson.Rows[e.RowIndex].FindControl("tbLastName")).Text;

            // Exit edit mode.
            gvPerson.EditIndex = -1;

            // Rebind the GridView control to show data after updating.
            BindGridView();

            // Show the Add button.
            lbtnAdd.Visible = true;
        }
    }

    // GridView.RowDeleting Event
    protected void gvPerson_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        if (ViewState["dtPerson"] != null)
        {
            // Get the DataTable from ViewState.
            DataTable dtPerson = (DataTable)ViewState["dtPerson"];

            // Get the PersonID of the selected row.
            string strPersonId = gvPerson.Rows[e.RowIndex].Cells[2].Text;

            // Find the row in DateTable.
            DataRow drPerson = dtPerson.Rows.Find(strPersonId);

            // Remove the row from the DataTable.
            dtPerson.Rows.Remove(drPerson);

            // Rebind the GridView control to show data after deleting.
            BindGridView();
        }
    }

    // GridView.Sorting Event
    protected void gvPerson_Sorting(object sender, GridViewSortEventArgs e)
    {
        string[] strSortExpression = ViewState["SortExpression"].ToString().Split(' ');

        // If the sorting column is the same as the previous one,
        // then change the sort order.
        if (strSortExpression[0] == e.SortExpression)
        {
            if (strSortExpression[1] == "ASC")
            {
                ViewState["SortExpression"] = e.SortExpression + " " + "DESC";
            }
            else
            {
                ViewState["SortExpression"] = e.SortExpression + " " + "ASC";
            }
        }
        // If sorting column is another column,
        // then specify the sort order to "Ascending".
        else
        {
            ViewState["SortExpression"] = e.SortExpression + " " + "ASC";
        }

        // Rebind the GridView control to show sorted data.
        BindGridView();
    }

    protected void lbtnAdd_Click(object sender, EventArgs e)
    {
        // Hide the Add button and showing Add panel.
        lbtnAdd.Visible = false;
        pnlAdd.Visible = true;
    }

    protected void lbtnSubmit_Click(object sender, EventArgs e)
    {
        if (ViewState["dtPerson"] != null)
        {
            // Get the DataTable from ViewState and inserting new data to it.
            DataTable dtPerson = (DataTable)ViewState["dtPerson"];

            // Add the new row.
            dtPerson.Rows.Add(null,  tbFirstName.Text,tbLastName.Text);

            // Rebind the GridView control to show inserted data.
            BindGridView();
        }

        // Empty the TextBox controls.
        tbLastName.Text = string.Empty;
        tbFirstName.Text = string.Empty;

        // Show the Add button and hiding the Add panel.
        lbtnAdd.Visible = true;
        pnlAdd.Visible = false;
    }

    protected void lbtnCancel_Click(object sender, EventArgs e)
    {
        // Empty the TextBox controls.
        tbLastName.Text = string.Empty;
        tbFirstName.Text = string.Empty;

        // Show the Add button and hiding the Add panel.
        lbtnAdd.Visible = true;
        pnlAdd.Visible = false;
    } 
}

No comments:

All Rights Reserved by Etechpulse © 2015 - 2016
Powered By Blogger

Contact Form

Name

Email *

Message *

Powered by Blogger.