GRID VIEW PPT

2,850 views 50 slides Jan 07, 2019
Slide 1
Slide 1 of 50
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50

About This Presentation

POWERPOINT


Slide Content

GRID VIEW

I have seen lot of beginners struggle with GridView and it is not working . To solve this to some extent, I have created an application with most of the events and properties of GridView . This may be helpful for getting a clear idea about working with GridView . This application also has a few JavaScript code snippets and stylesheets which may be useful to add some values to the GridView . Hope this article will be simple and sufficient. Introduction

The DataGrid or GridView control displays data in tabular form, and it also supports selecting, sorting, paging, and editing the data inside the grid itself. The DataGrid or GridView generates a BoundColumn for each field in the data source ( AutoGenerateColumns=true ). By directly assigning the data source to the GridView , the data can be rendered in separate columns, in the order it occurs in the data source. By default, the field names appear in the grid's column headers, and values are rendered in text labels. A default format is applied to non-string values and it can be changed. What is a GridView ?

The GridView control displays the values of a data source in a table. Each column represents a field, while each row represents a record.

Binding to data source controls, such as SqlDataSource . Built-in sort capabilities. Built-in update and delete capabilities. Built-in paging capabilities. Built-in row selection capabilities. Programmatic access to the GridView object model to dynamically set properties, handle events, and so on. Multiple key fields. Multiple data fields for the hyperlink columns. Customizable appearance through themes and styles. The GridView control supports the following features:

< asp:GridView  ID=" gridService "  runat =" server”>    </ asp:GridView >   This article shows how to use a GridView control in ASP.Net using C# code behind . Creating a GridView

In this we perform the following operations on GridView . Bind data to GridView column Edit data in GridView Delete rows from GridView Update row from database I have a sample example that explains all the preceding operations.

GridView is most feature-rich control in ASP.NET. Apart from displaying the data, you can perform select, sort, page, and edit operations with GridView control. Working with GridView in ASP.NET

If your application is working with huge amount of data, then it is not good and efficient to display all records at a time. Paging is a technique, which divides the records into pages. In DataGrid , the default page size is ten. The DataGrid supports two kinds of paging:   1. Default paging, and 2. Custom paging In default paging, the entire records are fetched from the database, then the DataGrid selects records from entire set of data, according to page size, to display it in DataGrid . Paging and sorting with GridView

In custom paging, developers have to write code for selective retrieve of the records from entire records to display in each page. Custom paging provides better performance than default paging. To enable default paging, set the AllowPaging property of the GridView to true. Default value of PageSize property is 10. Set PageSize property to display the number of records per page according to need of your application. The default event of DataGrid control is SelectedIndexChanged . The main event that is responsible for paging is PageIndexChanged event.

When the user clicks on paging link on the GridView , page is postback to the server. On postback , PageIndexChanged event of DataGrid is called. Set the PageIndex property of DataGrid is as follows. GridView1.PageIndex = e.NewPageIndex ; When user clicks on the paging link, new page index is set. GridView supports bidirectional paging. To enable sorting, set the AllowSorting property of the GridView as true . The main event behind sorting in GridView is Sorting event. protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) { }

GridViewSortEventArgs parameter supports SortDirection and SortExpression property. SortDirection property is used to sort the grid column using ascending and descending order. SortExpression property is the column name that you need to sort.

EXAMPLE :

Example using System; using System.Data ; using System.Data.SqlClient ; using System.Configuration ; using System.Web.UI.WebControls ; public partial class GridViewDemo : System.Web.UI.Page {   SqlConnection conn ;         SqlDataAdapter adapter;         DataSet ds ;        string str =" EmpID ";        protected void Page_Load (object sender, EventArgs e)        {               if(! IsPostBack )               {                       FillGridView ( str );               }        }       

   protected void FillGridView (string str )        {               string cs = ConfigurationManager.ConnectionStrings [" conString "]. ConnectionString ;               try               {                       conn = new SqlConnection ( cs );                      adapter = new SqlDataAdapter ("select * from tblEmps order by "+ str , conn );                       ds = new DataSet ();                       adapter.Fill ( ds );                      GridView1.DataSource = ds ;                      GridView1.DataBind();               }                  catch (Exception ex)               {                      Label1.Text = "ERROR :: " + ex.Message ;               }             

finally               {                       ds.Dispose ();                       conn.Dispose ();               }}          protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)        {                str = e.SortExpression ;                FillGridView ( str );        }        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)        {               GridView1.PageIndex= e.NewPageIndex ;                FillGridView ( str );        } } Execute the above code, you will get the output according to data in the database table. Default value of PageSize property is 10. We have set this value as 4

Therefore you will see the four records in GridView , at each page.

When you click on the next link, you will get the next records.

If you click on any column, record will be sort accordingly.

Suppose that there is no data in database table or no results are returned from the data source then you can display user friendly message in GridView that there is no record available. The GridView supports two properties that are used to display message when no results are returned. The two properties are: EmptyDataText EmptyDataTemplate Displaying Empty Data

Column Name Description BoundColumn To control the order and rendering of columns. HyperLinkColumn Presents the bound data in HyperLink controls ButtonColumn Bubbles a user command from within a row to the grid event handler TemplateColumn Controls which controls are rendered in the column CommandField Displays Edit, Update, and Cancel links in response to changes in the DataGrid control's EditItemIndex property. Using Fields with the GridView Control GridView Fields

By explicitly creating a BoundColumn in the grid's Columns collection, the order and rendering of each column can be controlled . In the BoundField properties, when the DataField and the SortExpressions are given, sorting and rendering the data can be easily done . BoundColumn

DataField : It bounds the column data of database table. DataFormatString : This property is used for string formats. HeaderText : It displays the custom header text on GridView . ReadOnly : It makes the field as non-editable. Visible : It is a Boolean property that enables you to make the column visible or hide according to value true or false. NullDisplayText : If there is no data in table, then you can use this property to display NULL message. Important properties of the BoundField class of the DataGrid

You can use BoundField by using the smart tag of GridView control as follows.

Click on Edit column link and provide text on HeaderText and DataField . Uncheck the Auto-generate fields’ checkbox.

A HyperLinkColumn presents the bound data in HyperLink controls . This is typically used to navigate from an item in the grid to a Details view on another page by directly assigning the page URL in NavigationUrl or by rendering it from the database. HyperLinkColumn

With a TemplateColumn , the controls which are rendered in the column and the data fields bound to the controls can be controlled . By using the TemplateColumn , any type of data control can be inserted . TemplateColumn

AlternatingItemTemplate : This template is used to display the content at every alternate row. EditItemTemplate : It is used when the user edit the records. FooterTemplate : As it name suggests that the contents of this template are displayed at the column footer. HeaderTemplate : It displayed the contents at the column header. InsertItemTemplate : When user inserted a new data item, then the contents of this template are displayed ItemTemplate : This template is used for every when rendered by the GridView . TemplateField in GridView supports the following six types of templates:

The EditCommandColumn is a special column type that supports in-place editing of the data in one row in the grid . EditCommandColumn interacts with another property of the grid: EditItemIndex . By default, the value of EditItemIndex is -1, meaning none of the rows (items) in the grid are being edited . If EditItemIndex is -1, an "edit" button is displayed in the EditCommandColumn for each of the rows in the grid. When the "edit" button is clicked, the grid's EditCommand event is thrown. When EditItemIndex is set to a particular row, the EditCommandColumn displays "update" and "cancel" buttons for that row . These buttons cause the UpdateCommand and CancelCommand events to be thrown, respectively. CommandField

Name Description DataBinding Occurs when the server control binds to a data source. (Inherited from Control.) DataBound Occurs after the server control binds to a data source. (Inherited from BaseDataBoundControl.) Disposed Occurs when a server control is released from memory, which is the last stage of the server control lifecycle when an ASP.NET page is requested. (Inherited from Control.) Init Occurs when the server control is initialized, which is the first step in its lifecycle. (Inherited from Control.) Load Occurs when the server control is loaded into the Page object. (Inherited from Control.) PageIndexChanged Occurs when one of the pager buttons is clicked, but after the GridView control handles the paging operation. PageIndexChanging Occurs when one of the pager buttons is clicked, but before the GridView control handles the paging operation. Different Types of Events

PreRender Occurs after the Control object is loaded but prior to rendering. (Inherited from Control.) RowCancelingEdit Occurs when the Cancel button of a row in edit mode is clicked, but before the row exits edit mode. RowCommand Occurs when a button is clicked in a GridView control. RowCreated Occurs when a row is created in a GridView control. RowDataBound Occurs when a data row is bound to data in a GridView control. RowDeleted Occurs when a row's Delete button is clicked, but after the GridView control deletes the row. RowDeleting Occurs when a row's Delete button is clicked, but before the GridView control deletes the row.

RowEditing Occurs when a row's Edit button is clicked, but before the GridView control enters edit mode. RowUpdated Occurs when a row's Update button is clicked, but after the GridView control updates the row. RowUpdating Occurs when a row's Update button is clicked, but before the GridView control updates the row. SelectedIndexChanged Occurs when a row's Select button is clicked, but after the GridView control handles the select operation. SelectedIndexChanging Occurs when a row's Select button is clicked, but before the GridView control handles the select operation. Sorted Occurs when the hyperlink to sort a column is clicked, but after the GridView control handles the sort operation. Sorting Occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation. Unload Occurs when the server control is unloaded from memory. (Inherited from Control.)

This event occurs when the property of the grid AllowPaging is set to true , and in the code behind the PageIndexChanging event is fired. Pageindexchanging

The DataGrid provides the means to display a group of records from the data source and then navigates to the "page" containing the next 10 records, and so on through the data. Paging in DataGrid is enabled by setting AllowPaging to true . When enabled, the grid will display page navigation buttons either as "next/previous" buttons or as numeric buttons. When a page navigation button is clicked, the PageIndexChanged event is thrown. It's up to the programmer to handle this event in the code. PAGING

The DataGrid fires the RowUpdating event when the command name is given as Update. OnRowUpdating ="GridView3_RowUpdating"  CommandName ="update"protected void GridView3_RowUpdating(object sender, GridViewUpdateEventArgs e ){ GridView3.EditIndex = e.RowIndex; GridView3.DataSource = Temp; GridView3.DataBind ();} AllowPaging="True"  AllowPaging is set to TrueGridView2.PageIndex = e.NewPageIndex;//Datasource methodTempTable(); RowUpdating

The DataGrid fires the RowEditing event when the command name is given as Edit. OnRowEditing =" GridView3_RowEditing“  protected void GridView3_RowEditing(object sender, GridViewEditEventArgs e){ GridView3.EditIndex = e.NewEditIndex - 1; int row = e.NewEditIndex; Temp.Rows[row]["name "] (( TextBox)GridView3.Rows[e.NewEditIndex].FindControl( "txtname")).Text; Temp.Rows[row]["gender"] = ((DropDownList)GridView3.Rows[e.NewEditIndex].FindControl( "ddlgender")).Text; RowEditing

Temp.Rows[row]["email"] = ((TextBox)GridView3.Rows[e.NewEditIndex].FindControl( "txtemail")).Text; Temp.Rows[row]["salary"] =((TextBox)GridView3.Rows[e.NewEditIndex].FindControl( "txtsalary")).Text; Temp.AcceptChanges(); Total = decimal.Parse(Temp.Compute("sum(Salary)", "Salary>=0").ToString()); Session["Salary"] = Total; GridView3.DataSource = Temp; GridView3.DataBind();}

Word protected void btnword_Click(object sender, EventArgs e){ Response.AddHeader("content-disposition", "attachment;filename=Information.doc"); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.word"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); Export GridView to Word, Excel, and PDF

System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); // Create a form to contain the grid HtmlForm frm = new HtmlForm(); GridView1.Parent.Controls.Add(frm); frm.Attributes["runat"] = "server"; frm.Controls.Add(GridView1); frm.RenderControl(htmlWrite); //GridView1.RenderControl(htw); Response.Write(stringWrite.ToString()); Response.End();}

protected void btnexcel_Click(object sender, EventArgs e){ string attachment = "attachment; filename=Information.xls "; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); HtmlForm frm = new HtmlForm(); GridView1.Parent.Controls.Add(frm); frm.Attributes ["runat"] = "server"; frm.Controls.Add(GridView1); frm.RenderControl(htw ); / Response.Write(sw.ToString()); Response.End();} Excel

protected void btnpdf_Click(object sender, EventArgs e){ Response.Clear(); StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); GridView1.RenderControl(htw); Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment; filename=Information.pdf"); Response.Write(sw.ToString()); Response.End();} PDF

Cells : It provides the cell collection of table row which is being bound. DataItem : It represents the data item which is going to bind with row. RowIndex : It provides the index of the bound row. RowState : It supports the following values. Alternate, Normal, Selected, and Edit. RowType : It provides the information about the type of row that is going to bound. It supports the following values. DataRow , Footer, Header, NullRow , Pager, and Separator. Some of the useful properties are as follows:

This is my second article, and if you have any questions, you can refer to the project attached because all the code in the article is from the project . Further questions or clarifications or mistakes are welcome. CONCLUSION
Tags