Monday, 2 April 2018

027 Asp.Net GridView

Gridview Control
Gridview display data in tabular format. Is widely used Asp.net controls and most popular and easy to use server control. Gridview not only display data, but also sorting, paging can be done in it. For styling Gridview , you can also apply Css in it .Gridview also allow inline editing, deleting data .You can display image in Gridview cell. It is possible to select a full row of a Gridview. Gridview may contain multiple keys and multiple data field.

                                       Gridview bind data with data source and populate automatically. You can also programmatically populate Gridview and it's row and cells. Gridview data source maybe DataSet or a collection.  When you bind a data source with Gridview, the column is generated automatically depending upon the data source. You can stop this functionality to make AutoGenerateColumns to false. Item template is a template of item which can be designed during design time. We will find an example of item template in later example. Gridview comes under the namespace System.Web.UI.WebControls

Here are some most common attributes of Gridview
 
 Constructor Gridview()  Initialised Gridview constructor to create a new instance of a Gridview.
Property AllowPaging  This property allow paging automatically.
Property AllowSorting  This property allow Grid column to sort automatically.
Property AllowSorting  This property allow Grid column to sort automatically.
Property AutoGenerateColumns  This property allow Gridview to generate column automatically or not.
Property AutoGenerateDeleteButton  This property allowed Gridview to generate auto delete Button or not.
Property AutoGenerateSelectButton  This property allow Gridview to generate automatically select Button or not.
Property ClientID  Get client ID from HTML generated from server. The ID is generated from server to render HTML to identify this control.
Property CssClass  Get or Set Stylesheet class for Gridview.
Property DataSourceID  Get or Set control id of bound data.
Method DataBind  Bind the Gridview with data source.
Method DeleteRow  Delete record from data source with the help of index.
Method Dispose  Dispose the Gridview and release all memories consumed by the Gridview.
Method FindControl  Search for a server control with parameter to identify that control
Event Onload  Handle the event when the Gridview is load.
Event PageIndexChanged  Handle the event,when page index is changed
Event OnRowCommand  Raise an event when command is fire against a row.
Event onRowDelete  Raised an event when delete command is fire against a row
Event onRowUpdate  Raise an event, when update command is fired against an update command.


Below is a script of table and some Sql  to insert data in this table. The script will create a table and fill with corresponding data. We are going to create some simple application of Gridview, we will use this table and data.

CREATE TABLE tbl_student
(
      ID INT IDENTITY,
      Name VARCHAR(500),
      Roll INT,
      Class INT
)
GO
INSERT INTO tbl_student(Name,Roll,Class)
VALUES('Student1',123,2)
GO
INSERT INTO tbl_student(Name,Roll,Class)
VALUES('Student2',124,3)
GO
INSERT INTO tbl_student(Name,Roll,Class)
VALUES('Student3',125,4)
GO
INSERT INTO tbl_student(Name,Roll,Class)
VALUES('Student4',126,5)
GO
INSERT INTO tbl_student(Name,Roll,Class)
VALUES('Student5',127,6)
GO
INSERT INTO tbl_student(Name,Roll,Class)
VALUES('Student6',128,7)
GO
INSERT INTO tbl_student(Name,Roll,Class)
VALUES('Student7',129,9)
GO
INSERT INTO tbl_student(Name,Roll,Class)
VALUES('Student8',130,10)



Here is some example of GridView

1) Populate GridView

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

<!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 runat="server">
                    <title></title>
            </head>
              <body>
                             <form id="form1" runat="server">
                                  <div>
                                         </div>
                                               <asp:GridView ID="GridView1" runat="server">
                                              </asp:GridView>
                                          </form>
                     </body>
                </html>

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

public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
         {
                      string conString = "Your Conncetion String";
                      DataSet ds = new DataSet();
                      SqlDataAdapter da = new SqlDataAdapter("select * from tbl_student ",  conString);
                      da.Fill(ds);
                      GridView1.DataSource = ds;
                      GridView1.DataBind();
        }
}

Output :
2) Paging , sorting and auto generated column of a gridview
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" PageSize="5">
</asp:GridView>
</form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
        protected void Page_Load(object sender, EventArgs e)
         {
                string conString = "Your Connection String";
                 DataSet ds = new DataSet();
                 SqlDataAdapter da = new SqlDataAdapter("select * from tbl_student ", conString);
                 da.Fill(ds);
                 GridView1.DataSource = ds;
                 GridView1.DataBind();
         }
}



3) GridView export to excel

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" EnableEventValidation = "false" EnableViewState="false" ValidateRequest= "false" %>

<!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 runat="server">
                         <title></title>
                  </head>
                     <body>
                                              <form id="form1" runat="server">
                                                 <asp:GridView ID="GridView1" runat="server"   AllowPaging="True"
AllowSorting="True" PageSize="5">
                                                 </asp:GridView>
                                                      <asp:Button ID="btnExport" runat="server" oncommand="btnExport_Command"
               Text="Export to Exel" />
               </form>
      </body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
            string conString = "your connection string;
             DataSet ds = new DataSet();
             SqlDataAdapter da = new SqlDataAdapter("select * from tbl_student ", conString);
             da.Fill(ds);
             GridView1.DataSource = ds;
             GridView1.DataBind();
}
protected void btnExport_Command(object sender, CommandEventArgs e)
{
         Response.Clear();
         Response.AddHeader("content-disposition", "attachment;filename=MyExel.xls");
         Response.Charset = "";
         Response.ContentType = "application/vnd.xls";
         StringWriter StringWriter = new System.IO.StringWriter();
         HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);

         GridView1.RenderControl(HtmlTextWriter);
         Response.Write(StringWriter.ToString());
         Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{

}
}
Output



4) GridView export to csv
 
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" EnableEventValidation = "false" EnableViewState="false" ValidateRequest= "false" %>

<!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 runat="server">
                              <title></title>
                     </head>
                           <body>
                                                         <form id="form1" runat="server">
                                                               <asp:GridView ID="GridView1" runat="server"  AllowPaging="True"
                                                       AllowSorting="True" PageSize="5">
                                                 </asp:GridView>
                                   <asp:Button ID="btnExport" runat="server" oncommand="btnExport_Command"
Text="Export to CSV" />
</form>
</body>
</html>

Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;

public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
                   string conString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\abanerjee\Desktop\WebSite1\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
                   DataSet ds = new DataSet();
                   SqlDataAdapter da = new SqlDataAdapter("select * from tbl_student ", conString);
                  da.Fill(ds);
                  GridView1.DataSource = ds;
                  GridView1.DataBind();
}
protected void btnExport_Command(object sender, CommandEventArgs e)
{

                   Response.Clear();
                   Response.Buffer = true;
                   Response.AddHeader("content-disposition", "attachment;filename=MyCSVFile.csv");
                   Response.Charset = "";
                   Response.ContentType = "application/text";
StringBuilder sb = new System.Text.StringBuilder();
                  for (int index = 0; index < GridView1.Columns.Count; index++)
                 {
                        sb.Append(GridView1.Columns[index].HeaderText + ',');
                  }
                sb.Append("\r\n");
               for (int i = 0; i < GridView1.Rows.Count; i++)
                {
                           for (int k = 0; k < GridView1.HeaderRow.Cells.Count; k++)
                           {
                                  sb.Append(GridView1.Rows[i].Cells[k].Text.Replace(",", "") + ",");
                           }
                          sb.Append("\r\n");
               }
                  Response.Output.Write(sb.ToString());
                  Response.Flush();
                  Response.End();
}
    public override void VerifyRenderingInServerForm(Control control)
   {

   }
}

Output


No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...