Saturday, July 5, 2014

The GridView Control

GridView in ASP.NET is used to display items in Table format. GridView control is just like a DataGrid. The GridView control provides the following functionality:
Ø  Database table-like presentation of data.
Ø  Table headers and footers.
Ø  Paging.
Ø  Sorting.
Ø  Selecting.
Ø  Style modification through templates.
Ø  Customizable columns for advanced editing.
Note that these are the only fields which we can use in a GridView control.

Field
Description
asp:BoundField
Enables us to display the value of a data item in a data source as text
asp:ButtonField
Enables us to display a button or the value of a data item as a button
asp:CheckBoxField
Enables us to display the value of a data item as a check box
asp:CommandField
Displays select, edit, delete, update or cancel buttons
asp:HyperLinkField
Displays a hyperlink
asp:ImageField
Displays an image
asp:TemplateField
Enables customization of the appearance of a data item
We can create Template Field’s in the GridView control using <TemplateField> element.

Steps to create the <TemplateField> element in the GridView control.

Ø  Declare the GridView and set the AutoGenerateColumns property to 'false'.
Ø  Create a Template column using <asp:TemplateField> tag within the <Columns> element.
Ø  Create <ItemTemplate> within the <asp:TemplateField> element to display value of field as text.
Ø  Create <EditItemTemplate> to display TextBox control to modify value of field when editing the record.
The GridView control supports the following templates:

Template Type
Description
AlternatingItemTemplate
The contents of this template are displayed for every other row rendered by the GridView
EditItemTemplate
The contents of this template are displayed when a row is selected for editing
FooterTemplate
The contents of this template are displayed in the column footer
HeaderTemplate
The contents of this template are displayed in the column header
InsertTemplate
The contents of this template are displayed when a new data item is inserted
ItemTemplate
The contents of this template are displayed for every row rendered by the GridView

GridView control has the following important members.

Properties:-

Property
Description
AllowPaging
Indicates whether paging is enabled
PageSize
Used to specify the number of pages to display per page
PagerSettings
Used to specify the settings related to pager like mode of the pager, position and caption of image to display for buttons like first, next, previous and last with in the pager
PageIndex
Used to get or set index of the current page displayed
AllowSorting
Indicates whether sorting is enabled
AutogenerateColumns
Indicates whether columns are automatically generated
AutogenerateDeleteButton
Indicates whether Delete button is provided for every row
AutogenerateEditButton
Indicates whether Edit button is provided for every row
AutogenerateSelectButton
Indicates whether Select button is provided for every row
Columns
Collection of columns in GridView
DataKeyNames
Used to specify the primary key column names of the table displayed in GridView
DataSource
Used to specify the source of data for the GridView that can be either a dataset or data reader
DataSourceId
Used to specify id of the data source control to bind to the GridView
EditIndex
Used to get or set index of the row that is currently in edit mode
EmptyDataText
Used to specify the text to display with in the GridView when data source is empty
EnableSortingAndPagingCallbacks
Indicates whether only GridView is posted back to server and updated from server during sorting and paging without causing entire page postback
ShowHeader
Indicates whether header is displayed
ShowFooter
Indicates whether footer is displayed
HeaderRow
Provides access to header row within the GridView
FooterRow
Provides access to footer row in the GridView
Rows
Collection of rows in the grid view
SelectedIndex
Used to get or set index of the row that is selected
SelectedValue
Returns the primary key value of the selected row and for this DataKeyNames property must be set
SelectedRow
Provides access to the Selected row

Events:-

Event
Description
SelectedIndexChanging
Raised whenever user select a row
RowEditing
Raised whenever user click on Edit link button
RowCancellingEdit
Raised whenever user click on cancel link button
RowUpdating
Raised whenever user click on update button
RowDeleting
Raised whenever user click on delete button
Sorting
Raised whenever user click on column header to sort the rows
PageIndexChanging
Raised whenever user move to a new Page

Example1:- The following example provides access to the table dept available in the database mydb of Sql Server declaratively using SqlDataSource control and allows the user to perform update, delete, paging, sorting and select.

1.      Add a page to the website, take a SqlDataSource control on it and configure it to access the table dept available in mydb database of Sql server and while configuring in the step where you select the table to access click on advanced button and within advanced dialog box check both the check boxes.
2.      Take a GridView control on the page and set DataSourceID property of it to the id of SqlDataSource control created in first step.
3.      When you run the page then the data retrieved from the table dept will be displayed in the grid view.
4.      To allow the user to edit the values of a row and update them to database set autogenerateeditbuttoon property of the GridView to true to provide edit button for every row in the GridView. At runtime when you click on edit button for a row then that row will be converted to edit mode and in the place of edit button you will get two buttons update and cancel. Clicking on cancel button will cancel editing and clicking on update button will update the changes to database.
5.      To allow the user to delete rows, set autogeneratedeletebutton property to true for the GridView that provides delete button for every row in the grid view. Clicking on delete button for a row will delete that row from GridView as well as from database.
6.      To allow user to sort the rows set allowsorting property of the GridView to true that makes the column headings displayed like hyperlinks and clicking on a column heading will sort the sort the rows in ascending order of that column and clicking on the same column header again will arrange the rows in descending order of that button.
7.      To apply paging for the grid view, set allowpaging property to true page size to 2 and also set any pager settings you want. At runtime within the pager when you click on a page number then the corresponding page will be displayed.
8.      To allow the user to select a row set autogenerateselectbutton property to true that provides select button for every row in the GridView. Now to display the employees list working in selected department in another GridView, take another SqlDataSource control and configure it to access the table emp available in mydb database of SQL Server and while configuring it in the step where you select the table, click on the button where and set following properties for it and click on add button followed by ok button.
Column           : DEPTNO
Operator        : =
Source                        : control
Control ID       : GridView1
9.      Take another GridView on the page and set its DataSourceID property to the id of SqlDataSource control created in previous step. At runtime when you select a department then the list of employees working in that department will be displayed in this GridView. For this GridView  set EmptyDataText property to “Which can be displayed in web page“ so that when there are no employees in the selected department then this text will be displayed in GridView.

Example2: The following example provides access to the table Tutorial available in mydb database of Sql server using GridView by writing the code manual without using any DataSource control.
1.      Add a page to the website, take a GridView control on it, set id of GridView control as GridView1, AutoGenerateColumns property of the GridView to true and within html source of the page create columns for the GridView using template fields as follows.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowFooter="True" EnableViewState="False" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowCommand="GridView1_RowCommand" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" PageSize="2" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" OnSelectedIndexChanging="GridView1_SelectedIndexChanging">
<Columns>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="LnkEdit" runat="server" Text="Edit" CommandName="Edit" />
<asp:LinkButton ID="LnkDelete" runat="server" Text="Delete" CommandName="Delete" />
<asp:LinkButton ID="LnkSelect" runat="server" Text="Select" CommandName="Select" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LnkUpdate" runat="server" Text="Update" CommandName="Update" />
<asp:LinkButton ID="LnkCancel" runat="server" Text="Cancel" CommandName="Cancel" />                       
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="LnkInsert" runat="server" Text="Insert" CommandName="Insert" />
<asp:LinkButton ID="LnkCancel" runat="server" Text="Cancel" CommandName="Cancel" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" >
<ItemTemplate>
<asp:Label ID="LblId" runat="server" Text='<%#Eval("id") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="LblId" runat="server" Text='<%#Eval("id") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TxtId" runat="server" Text="<%#Bind('id') %>" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject ID" >
<ItemTemplate>
<asp:Label ID="LblSid" runat="server" Text='<%#Eval("subid") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TxtSid" runat="server" Text="<%#Bind('subid') %>" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TxtSid" runat="server" Text="<%#Bind('subid') %>" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject" >
<ItemTemplate>
<asp:Label ID="LblSub" runat="server" Text='<%#Eval("subject") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TxtSub" runat="server" Text="<%#Bind('subject') %>" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TxtSub" runat="server" Text="<%#Bind('subject') %>" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tutorial Name" >
<ItemTemplate>
<asp:Label ID="LblTname" runat="server" Text='<%#Eval("tname") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TxtTname" runat="server" Text="<%#Bind('tname') %>" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TxtTname" runat="server" Text="<%#Bind('tname') %>" />
</FooterTemplate>
</asp:TemplateField>          
</Columns>           
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>


<asp:GridView ID="GridView2" runat="server" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
        </asp:GridView>

            2.      Now In the web.config file create the connection string as:
<connectionStrings><add name="constr" connectionString="uid=sa;pwd=nagesh;database=nagesh;" providerName="System.Data.SqlClient"/>
</connectionStrings>

3.      Within the globally in the page declare objects for the classes SqlConnection, SqlDataAdapter, SqlCommandBuilder and DataSet and then create a method with the name fillgrid as follows and call it in the page load event.

SqlConnection cn = new SqlConnection(WebConfigurationManager.ConnectionStrings["constr"].ConnectionString);
    SqlDataAdapter da;
    SqlCommandBuilder cmb;
    DataSet ds;
    public void fillgrid()
    {
        da = new SqlDataAdapter("select * from Tutorial", cn);
        cmb = new SqlCommandBuilder(da);
        ds = new DataSet();
        da.Fill(ds, " Tutorial ");
        GridView1.DataSource = ds.Tables["Tutorial "];
        GridView1.DataBind();
        GridView1.DataKeyNames = new string[] { "id" };
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        fillgrid();
    }

4.      Write the following code within the RowCommand event of the GridView to insert the row.

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Insert")
        {
            GridViewRow gr = GridView1.FooterRow;
           // TextBox t1 = gr.FindControl("TxtId") as TextBox;//this is primary key coloumn it has identity is true
            TextBox t2 = gr.FindControl("TxtSid") as TextBox;
            TextBox t3 = gr.FindControl("TxtSub") as TextBox;
            TextBox t4 = gr.FindControl("TxtTname") as TextBox;
            DataRow dr = ds.Tables["Tutorial "].NewRow();
           // dr[0]=t1.Text;
            dr[1] = t2.Text;
            dr[2] = t3.Text;
            dr[3] = t4.Text;
            ds.Tables["Tutorial "].Rows.Add(dr);
            da.Update(ds, " Tutorial ");
            fillgrid();
        }
    }

5.      Write the following code within the RowEditing, RowCancellingEdit, RowDeleting and RowUpdating events of the GridView to allow user to edit data and update it.

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        fillgrid();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        fillgrid();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow gr1 = GridView1.Rows[e.RowIndex];
        TextBox t2 = gr1.FindControl("TxtSid") as TextBox;
        TextBox t3 = gr1.FindControl("TxtSub") as TextBox;
        TextBox t4 = gr1.FindControl("TxtTname") as TextBox;
        DataRow dr = ds.Tables["example"].Rows[e.RowIndex];
        dr[1] = t2.Text;
        dr[2] = t3.Text;
        dr[3] = t4.Text;
        da.Update(ds, "example");
        GridView1.EditIndex = -1;
        fillgrid();

    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        ds.Tables["example"].Rows[e.RowIndex].Delete();
        da.Update(ds, "example");
        fillgrid();
    }

6.      Take another GridView control on the page set id as gridview2 and write the following code within selectedindexchanging event of the gridview1 to displaythe list of tutorials in selected subjected.

   protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        GridView1.SelectedIndex = e.NewSelectedIndex;
        string id = GridView1.SelectedValue.ToString(); SqlDataAdapter da1 = new SqlDataAdapter("select * from example where subid=" + id, cn);
        DataSet ds1 = new DataSet();
        da1.Fill(ds1, "tut");
        GridView2.DataSource = ds1.Tables["tut"];
        GridView2.DataBind();
    }

7.      Set allow paging property of the gridview1 page size property to 2 and then write the following code within the PageIndexChanging event of the gridview1 to allow the user to navigate between pages.

          protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        fillgrid();
    }

2 comments:

  1. Hi! Nagesh please post tutorials for all controls

    ReplyDelete
  2. good explaination thanku

    ReplyDelete