Go to DotNetFunda.com
 Online : 237 |  Welcome, Guest!   Login
 
<<= Please see left side tutorials menu.

  • Nominate yourself for "ADO.NET" online training session tomorrow (13-Mar-2010) for FREE, click here.

  • Download OOPS and ASP.NET Online training session video and PPT from here.


Silverlight Tutorials | Report a Bug in the Tutorial

Interesting?   Share and Bookmark this

asp:GridView control
GridView control is a successor to the ASP.NET 1.X DataGrid control.
 
GridView control is a successor to the ASP.NET 1.X DataGrid control. It provides more flexibility in displaying and working with data from your database in comparison with any other controls. The GridView control enables you to connect to a datasource and display data is tabular format, however you have bunch of options to customize the look and feel. When it is rendered on the page, generally it is implemented through <table> HTML tag.

Its properties like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, Height etc. are implemented through style properites of <tahle> tag.

Following are some important properties that are very useful.
Behavior Properties of the GridView Control
AllowPaging true/false. Indicate whether the control should support paging.
AllowSorting true/false. Indicate whether the control should support sorting.
SortExpression Gets the current sort expression (field name) that determines the order of the row.
SortDirection Gets the sorting direction of the column sorted currently (Ascending/Descending).
DataSource Gets or sets the data source object that contains the data to populate the control.
DataSourceID Indicate the bound data source control to use (Generally used when we are using SqlDataSource or AccessDataSource to bind the data, See 1st Grid example).
AutoGenerateEditButton true/false. Indicates whether a separate column should be added to edit the record.
AutoGenerateDeleteButton true/false. Indicates whether a separate column should be added to delete the record.
AutoGenerateSelectButton true/false. Indicate whether a separate column should be added to selecat a particular record.
AutoGenerateColumns true/false. Indicate whether columns are automatically created for each field of the data source. The default is true.
Style Properties of the GridView Control
AlternatingRowStyle Defines the style properties for every alternate row in the GridView.
EditRowStyle Defines the style properties for the row in EditView (When you click Edit button for a row, the row will appear in this style).
RowStyle Defines the style properties of the rows of the GridView.
PagerStyle Defines the style properties of Pager of the GridView. (If AllowPaging=true, the page number row appears in this style)
EmptyDataRowStyle Defines the style properties of the empty row, which appears if there is no records in the data source.
HeaderStyle Defines the style properties of the header of the GridView. (The column header appears in this style.)
FooterStyle Defines the style properties of the footer of GridView.
Appearance Properties of the GridView Control
CellPadding Indicates the space in pixel between the cells and the border of the GridView.
CellSpacing Indicates the space in pixel between cells.
GridLines Both/Horizontal/Vertical/None. Indicates whether GrdiLines should appear or not, if yes Horizontal, Vertical or Both.
HorizontalAlign Indicates the horizontal align of the GridView.
EmptyDataText Indicates the text to appear when there is no record in the data source.
ShowFooter Indicates whether the footer should appear or not.
ShowHeader Indicates whether the header should appear or not. (The column name of the GridView)
BackImageUrl Indicates the location of the image that should display as a background of the GridView.
Caption Gets or sets the caption of the GridView.
CaptionAlign left/center/right. Gets or sets the horizontal position of the GridView caption.
State Properties of GridView Control
Columns Gets the collection of objects that represent the columns in the GridView.
EditIndex Gets or sets the 0-based index that identifies the row currently to be edited.
FooterRow Returns a GridViewRow object that represents the footer of the GridView.
HeaderRow Returns a GridViewRow object that represents the header of the GridView.
PageCount Gets the number of the pages required to display the reocrds of the data source.
PageIndex Gets or sets the 0-based page index.
PageIndex Gets or sets the number of records to display in one page of GridView.
Rows Gets a collection of GridViewRow objects that represents the currently displayed rows in the GridView.
DataKeyNames Gets an array that contains the names of the primary key field of the currently displayed rows in the GridView.
DataKeys Gets a collection of DataKey objects that represent the value of the primary key fields set in DataKeyNames property of the GridView.
Events associated with GridView Control
PageIndexChanging, PageIndexChanged Both events occur when the page link is clicked. They fire before and after GridView handles the paging operation respectively.
RowCancelingEdit Fires when Cancel button is clicked in Edit mode of GridView.
RowCommand Fires when a button is clicked on any row of GridView.
RowCreated Fires when a new row is created in GridView.
RowDataBound Fires when row is bound to the data in GridView.
RowDeleting,RowDeleted Both events fires when Delete button of a row is clicked. They fire before and after GridView handles deleting operaton of the row respectively.
RowEditing Fires when a Edit button of a row is clicked but before the GridView hanldes the Edit operation.
RowUpdating, RowUpdated Both events fire when a update button of a row is clicked. They fire before and after GridView control update operation respectively.
Sorting, Sorted Both events fire when column header link is clicked. They fire before and after the GridView handler the Sort operation respectively.
DEMO : Button Show Source Code
1st Grid: Simple GridView with SqlDataSource
 Delete?AutoIDNameAddressPhoneCity
Edit Delete 392abbbaaa
Edit Delete 397adasdsadasdasdadasdadsdasd
Edit Delete 391asdfghjklghjkl 
Edit Delete 390asdfasdfasdfasdf
Edit Delete 401dzczcxzxczxczxczxxzczx
Edit Delete 396gfhgfhgfgfhfgfghgf
Edit Delete 400hhhh
Edit Delete 399kkkk
12345678
Note: Updating this GridView will not affect 2nd GridView listing unless you come to this page without page postback as that GridView data has been bound in not IsPostBack condition.
2nd Grid: GridView with CodeBehind Data Bound
AutoIDNameAddressPhoneCity
392abbbaaa
397adasdsadasdasdadasdadsdasd
391asdfghjklghjkl 
390asdfasdfasdfasdf
401dzczcxzxczxczxczxxzczx
396gfhgfhgfgfhfgfghgf
400hhhh
399kkkk
380Marakasadsfdsfdsfdsafdsafasdf
238ND545545DDF
387Payalsdasa043364+ASSDS
257rajchennai9942350800chennai
260raj123chennai9942350800chennai
369RajuHyd747473473hyd
374rgfsdfsdfgsdg
234rtyrrrrrrrrr
246ssss
376Sb732tempe
343ssss
346SGGG
398sadfsdfsdfsdfssdfssdfsdf
317sadxasdasdasd
324Sample345dfgdfg234324235cfgdfgdfg
226sangeethamadipakkam,PP22343223chennai
278sarveshusha1234567indore
254sdsdfsdfsd
334sdsdsdsd
379sdaasdf23234asdf
365sddghdhasdasdasd
315sdfsdfssfsdfsdfsd
277sdfsdfsdfsdf
340sdfsdfsfsdfdfsdfsdfsd
290sdfsdfsdfsdf
350sdfasdfasdfasdfa
378sdgsdfgsdfsfg
311SEEMADFCFERFERFRGFRE
345smHDS
302SovandyPhnom Penh017 855 431Phnom Penh
220Sovandya11017 855 431PP
341srinusr nagar9703735834Hyd
320sssss
250ssssss353656hyj
230ssssthtrhthtrhhrrthtr
244SSSSSIIIIIIIIdhh
402testtesttesttest
288TestTest12Testbxb
275testtesttesttest
273testtesttesttest
314testtesttesttest
372testtesttesttest
274testtesttesttest
245thulasidelhi9988765433delhi
325try67567567
236tttttsdfasdf353453fasdfasdfad
247TYUTYUTYU  
348u8uuuuasdfasdfasdf
342vidhyad3333dddd
225Vikas DeepDLF_39650273495Gurgaon
395visahlnand 1234delhi
367vivekpune1234556oos
360werewrsdfsd45645645645
384wqwq3wq4wqwqwq
                
// 1st GridView /////////////////////////
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Caption="1st Grid: Simple GridView with SqlDataSource"
     AllowPaging="True" AllowSorting="True" AutoGenerateEditButton="true" 
      DataKeyNames="AutoID" PageSize="8">
      <Columns>
        <asp:TemplateField HeaderText="Delete?">
            <ItemTemplate>
                <asp:LinkButton ID="lnk1" runat="server" Text="Delete" OnClientClick="return confirm('Are you sure to Delete?')" CommandName="Delete"></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
      </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString='<%$ ConnectionStrings:ConnStr %>'
     SelectCommand="Select * FROM SampleForTutorials ORDER BY [Name]"
     DeleteCommand="Delete FROM SampleForTutorials WHERE AutoID = @AutoID"
     UpdateCommand="UPDATE SampleForTutorials SET Name = @Name, Address = @Address, Phone = @Phone, City = @City WHERE AutoID = @AutoID">
        <DeleteParameters>
            <asp:Parameter Name="AutoID" />
        </DeleteParameters>
        <UpdateParameters>
            <asp:Parameter Name="AutoID" Type="Int32" />
            <asp:Parameter Name="Name" Type="string" Size="50" />
            <asp:Parameter Name="Address" Type="string" Size="200" />
            <asp:Parameter Name="Phone" Type="int32" />
            <asp:Parameter Name="City" Type="string" Size="20" />
        </UpdateParameters>
     </asp:SqlDataSource>
     
     
     // 2nd GridView /////////////////////////
<asp:GridView ID="GridView2" runat="server" BackColor="LightGoldenrodYellow" BorderColor="Tan"
 Caption="2nd Grid: GridView with CodeBehind Data Bound" AllowPaging="False" AllowSorting="False"
    BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None">
    <FooterStyle BackColor="Tan" />
    <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
    <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" Font-Bold="True" />
    <HeaderStyle BackColor="Tan" Font-Bold="True" />
    <AlternatingRowStyle BackColor="PaleGoldenrod" />
</asp:GridView>     
 
 
 // CODE BEHIND
 
// Bind the GridView /////////////////////////
private void BindGridView()
{
    string connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ToString();
    SqlConnection conn = new SqlConnection(connStr);
    conn.Open();
    SqlDataAdapter dAd = null;
    DataSet dSet = new DataSet();
    try
    {
        string strSql = "Select * FROM SampleForTutorials ORDER BY [Name]";
        dAd = new SqlDataAdapter(strSql, conn);
        dAd.Fill(dSet, "SampleTable");

        GridView2.DataSource = dSet.Tables["SampleTable"].DefaultView;
        GridView2.DataBind();
        
    }
    catch (Exception ee)
    {
        lblError.Text = "Error occured. <br>+" + ee.Message.ToString();
    }
    finally
    {
        dSet.Dispose();
        dAd.Dispose();
        conn.Close();
        conn.Dispose();
    }
}
     
                    




About Us | The Team | Advertise | Contact Us | Feedback | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found copied contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
All rights reserved to DotNetFunda.Com. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks.
(Best viewed in IE 6.0+ or Firefox 2.0+ at 1024 * 768 or higher)