Skip to main content

GridView Tips and Trics

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="GridViewComplete.aspx.cs"
   Inherits="GridViewComplete" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
   <title>Grid View Add Update Delete</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
              ShowFooter="true" AllowPaging="true"  PageSize="4"
              AllowSorting="True"
              OnRowCommand="GridView1_RowCommand"
              OnPageIndexChanging="GridView1_PageIndexChanging"
              OnRowDeleting="GridView1_RowDeleting"
              OnRowEditing="GridView1_RowEditing"
              OnRowUpdating="GridView1_RowUpdating"
              OnSorting="GridView1_Sorting"
              OnRowCancelingEdit="GridView1_RowCancelingEdit">
               <Columns>
                 <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
                  <asp:TemplateField HeaderText="Id" InsertVisible="False" SortExpression="Id">
                      <EditItemTemplate>
                          <asp:Label ID="Label1" runat="server"
Text='<%# Eval("Id") %>'></asp:Label>
                      </EditItemTemplate>
                      <ItemTemplate>
                          <asp:Label ID="Label1" runat="server"
Text='<%# Bind("Id") %>'></asp:Label>
                      </ItemTemplate>
                  </asp:TemplateField>
                   <asp:BoundField DataField="Id"  ShowHeader="True"/>
                  <asp:TemplateField HeaderText="Name" SortExpression="Name">
                      <EditItemTemplate>
                          <asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("Name") %>'></asp:TextBox>
                      </EditItemTemplate>
                      <ItemTemplate>
                          <asp:Label ID="Label2" runat="server"
 Text='<%# Bind("Name") %>'></asp:Label>
                      </ItemTemplate>
                      <FooterTemplate>
                          <asp:TextBox ID="QuantityTextBox" runat="server"></asp:TextBox>
                      </FooterTemplate>
                  </asp:TemplateField>
                  <asp:TemplateField HeaderText="Description" SortExpression="Description">
                      <EditItemTemplate>
                          <asp:TextBox ID="TextBox2" runat="server"
Text='<%# Bind("Description") %>'></asp:TextBox>
                      </EditItemTemplate>
                      <ItemTemplate>
                          <asp:Label ID="Label3" runat="server"
Text='<%# Bind("Description") %>'></asp:Label>
                      </ItemTemplate>
                      <FooterTemplate>
                          <asp:TextBox ID="DescriptionTextBox" runat="server"></asp:TextBox>
                      </FooterTemplate>
                  </asp:TemplateField>
                  <asp:TemplateField>
                     <FooterTemplate>
                          <asp:LinkButton ID="btnNew" runat="server"
CommandName="New" Text="New" />
                      </FooterTemplate>
                  </asp:TemplateField>
              </Columns>
          </asp:GridView>
       </div>
       <div style="color:Red">
       <asp:Label ID="lblMsg" runat="server"></asp:Label>
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class GridViewComplete : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
        if (!IsPostBack)
        {
            BindGrid();
          
        }
    }
    public void BindGrid()
    {


        if (Session["dt"] == null)
        {
            GridView1.DataSource = CreateDGDataSource();
            GridView1.DataBind();
        }
        else
        {

            GridView1.DataSource = Session["dt"] as DataTable;
            GridView1.DataBind();

        }



    }
    public DataTable CreateDGDataSource()
    {
        // Create sample data for the DataList control.
        DataTable dt = new DataTable();
        DataRow dr;
        int i;
        int y;
        // Define the columns of the table.
        dt.Columns.Add(new DataColumn("ID", typeof(int)));
        dt.Columns.Add(new DataColumn("Name", typeof(string)));
        dt.Columns.Add(new DataColumn("Description", typeof(string)));
        //Make some rows and put some sample data in
        for (i = 1; i <= 5; i++)
        {
            dr = dt.NewRow();
            dr[0] = i;
            dr[1] = "Name" + "-" + i;
            dr[2] = "Item " + "_" + i;
            //add the row to the datatable
            dt.Rows.Add(dr);
        }

        Session["y"] = i;
        Session["dt"] = dt;

        return dt;
    }

    public ICollection CreateDGDataSource(int CategoryID)
    {
        DataView dv = new DataView(CreateDGDataSource(), "ID=" + CategoryID, null,
            DataViewRowState.CurrentRows);
        return dv;

    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            if (e.CommandName.Equals("New"))
            {
                LinkButton btnNew = e.CommandSource as LinkButton;
                GridViewRow row = btnNew.NamingContainer as GridViewRow;
                if (row == null)
                {
                    return;
                }
                TextBox txtCatName = row.FindControl("QuantityTextBox") as TextBox;
                TextBox txtDescription = row.FindControl("DescriptionTextBox") as TextBox;
                DataTable dt = Session["dt"] as DataTable;
                DataRow dr;
                int intId = (int)Session["y"];
                dr = dt.NewRow();
                dr["Id"] = intId++;
                Session["y"] = intId;
                dr["Name"] = txtCatName.Text;
                dr["Description"] = txtDescription.Text;
                dt.Rows.Add(dr);
                dt.AcceptChanges();
                Session["dt"] = dt;

                GridView1.DataSource = Session["dt"] as DataTable;
                GridView1.DataBind();

            }

        }
        catch (Exception ex)
        {

        }


    }
   
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindGrid();
    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        DataTable dataTable = Session["dt"] as DataTable;
        if (dataTable != null)
        {
            DataView dataView = new DataView(dataTable);
            dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
            GridView1.DataSource = dataView;
            GridView1.DataBind();
        }
    }
    private string ConvertSortDirectionToSql(SortDirection sortDireciton)
    {
        string newSortDirection = String.Empty;
        switch (sortDireciton)
        {
            case SortDirection.Ascending:
                newSortDirection = "ASC";
                break;
            case SortDirection.Descending:
                newSortDirection = "DESC";
                break;
        }
        return newSortDirection;
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int ID = (int)GridView1.DataKeys[e.RowIndex].Value;
        // Query the database and get the values based on the ID and delete it.
        lblMsg.Text = "Deleted Record Id" +ID.ToString();
      
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindGrid();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
       
        // Retrieve the row being edited.
        int index = GridView1.EditIndex;
        GridViewRow row = GridView1.Rows[index];
        TextBox t1 = row.FindControl("TextBox1") as TextBox;
        TextBox t2 = row.FindControl("TextBox2") as TextBox;
        string t3 = GridView1.DataKeys[e.RowIndex].Value.ToString();

        lblMsg.Text = "Updated record " + t1.Text + "," + t2.Text + "Value From Bound Field" + t3;
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindGrid();
    }
}

Comments

Popular posts from this blog