What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 15246 |  Welcome, Guest!   Register  Login
Home > Tutorials > ASP.NET Tutorials > GridView control

Silverlight Tutorials | Report a Bug in the Tutorial
Found interesting? Add this to:


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 13359AAaAaA
Edit Delete 13331Johncccokkkkkkkkkk800ok
Edit Delete 13237sddfdfsdf
Edit Delete 12735sdasdasdasdasdasdasd
Edit Delete 13345sdasdaasdasdasdasdasdasd
Edit Delete 12825sddflklklklk
Edit Delete 13268sdfsdfdfdf
Edit Delete 13275sdfasdfasfasf
12345678910...
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
13359AAaAaA
13331Johncccokkkkkkkkkk800ok
13237sddfdfsdf
12735sdasdasdasdasdasdasd
13345sdasdaasdasdasdasdasdasd
12825sddflklklklk
13268sdfsdfdfdf
13275sdfasdfasfasf
12671sdfsafsdfsdf
12643sdfsdfsdfsdf
12144sdfsdfsdfsdf
12837sdfdsafdsfdsfsdafdsfdas
12214sdfhadfghsdfgasdfgh
13029sdfsdsfsdfsdfsfsdfs
12653sdgsdfgsgsfgsdgsdfgsdg
13293sdgdfsdfsdfsdfsdf
13251sdgsdgsdgsdgsdsdggsd
12516sdmamdfd5656yyuy
13223sdqfdfqsdqsdfqfsdq
13224sdqfdfqsdqsdfqfsdq
13225sdqfdfqsdqsdfqfsdq
13226sdqfdfqsdqsdfqfsdq
13220sdqfdfqsdqsdfqfsdq
13221sdqfdfqsdqsdfqfsdq
12340sdssdssddsd
12739sdsadaasdasdasdasdasasdasda
12056sdsdsdsdssd
12338sdsdsdssdssds
12707sdvcfererererererer
12901sdvdvvvcvcxxvvdsvdvdsdvdvsdv
13267sdvfbgvdsfvsfdgdsf
12228seds123sedssedsseds
12526sfdsfdfdf
12538sfsfsdfsdfsdfs
12268sfdsdfsdsdfsd
12130sfddsfsdsfsfsdfsfsdfsf
13163sfdssdfds7666dfffg
12082SFSDGsdfsdsdfsdsdf
12319shahsads65765765gdfdf
12313shahnawazalam8888888allahabad
12171shaikbangalore9987676543bangalore
12172shaikbangalore9987676543bangalore
12741shank12322333
12475ShankarnarayanShankarnarayanShankarnarayanShankarnarayan
13354shejinxcbcvbcvvbnvbn
12375shilpivikas 123456mathura
12661sibtainshah12-2---2karachi
12400sirilguntur 9988578960hyd
12417skindia00000000mm
12358skindia00000000MM
12921skahdhshdfsk212u30ansdkd
12133snahfhf858845chennai
13285snehakilpauk26432242chennai
12722snehasdfasdcascsacsac
12299sreetfd8888tnk
12810srihydernagar2738gurgan
12920Srinivasasdadsafd
12562srinubachibowli44444444444Hyderabad
12084srinuerrrt12233werr
12306sssssssss
12703sssssssss
12910ssss7667ddssd
13119sssssssss
13192sssssssss
12484sSsSsddeDDdfdD
12716sscc23432434cc
12374sssssssss
12344ssaasasasa
13020ssgdgqsfjdfgSDFSDasafagda
12964sssssss333dddd
13059sssssssssssssss
12405ssssssrrrrrrfffffaaaaa
12435stuart11212a city
12111subaskhkhhktoronto
12159subbufdffdffdf
12125subhashramnagar9457587589nsinital
12126subhashramnagar9457587589nsinital
13326Sudheer TankalaHno:10-5-134,Fathenagar09951627651Hyderabad
12556SunilSubhash Nagar9876543210Udaipur
12428Syed ZaidiAPT 811254558dallas
13356szdcsfxfdfdfdffddff
13361tttt
12211tttt
12163tttt
13193thfgh
12444t4t40gr
13032tdrtrtetretettret
12307tedtterer3434345346mum
13209tertertertreerter
12889Testtesttesttest
12743testtesttesttest
13069testtesttesttest
13274test   
13076testtesttesttest
12548testtestesttest
12549testtest234234sdfsdf
12342testtesttesttest
13363testtesttesttest
12293test123
12300TESTING905405940-9540909094MH
12298TESTING09403940349mum
12746testtesttesttest
13031testthishereok
13290testtesttesttest
12561testtesttesttest
12480testtesttesttest
12878testtesttesttest
12947testtesttesttest
13262testyyy
12074testtestadress9586257fgfdhkj
13142testvitkin11234567net
12482testtesttesttest
12129Test101sdfsdfsdfsdfsdfsdfsd
12576testetestetesteteste
12642testingawefawefaweffff
12170testttttttttestttttttttttttwattttttttwatttttt
12684tgyuynjikkiuhjnjnmyujnm v
13323ththfhtht
13322ththfhtht
12822ThantThiriMyoKyi
13212thulasi1247204744618bangalore
13335tidfgdffd
12410totoeee465465paris
13362trttt
12272trettretretretertretre
12626trhrtyrtyrtyrty
12713trytrydehi19875566441delhi
13231tsdhgdffdhg57445645645fg
13232tsdhgdffdhg57445645645fg
12220tttttttt
12221ttmit@testit.commit@testit.combb
13178ttrtgdfgdfgd9786786hfghf
13291tttttttttttt
12241tyrtrtyrtyrty
12242tyrtrtyrtyrty
12243tyrtrtyrtyrty
12244tyrtrtyrtyrty
12245tyrtrtyrtyrty
12246tyrtrtyrtyrty
12247tyrtrtyrtyrty
12248tyrtrtyrtyrty
12249tyrtrtyrtyrty
12250tyrtrtyrtyrty
12252tyrtrtyrtyrty
12253tyrtrtyrtyrty
13307tyutyuufghyugih
12852tyue5yu147q42s
13216tyutyututyututyu
13228tyyyghghg8585red
13087uiiu
12258u65u56uu56u56uaa
12485ueiADADDddDDd
12452ui9ojhhkjh
12778uikkghkkkyuyyy
13227uipyio[yio[yi[
12774ujwasdasdasd
12287UMASAH9766544
12263umair32321d12014521khi
12775ut6u67866786686
12059ututyuttyutuytyu66666vnfnhghfg
12365uuuuuuuuuuuu
12093uyfgyuguigugyugugugjbjhbjhbm
13120uyhukhgujfyt';ik';5645665  
13276uyyuyuyuyuyuuuyy
12809v1300 Elmwood AvegBuffalo
13300Varshalkabsklb898989898BANGALORE
12939vbsdvsdvsvsddsvsd
13325vbvvbnvbnvbn
13083venkatThi9000064443hyd
12162vffvffvvfvfvfvfvfv
12935vigneshpondy9962647896pondy
12970vigneshchennaioksdzkjhczjkchgoregoun
12229VijayPohwani6765669cbfhsdd
13338vijendrajaipur9950831083Jaipur
13337Vijendra Jaipur9950831083Jaipur
12473vishnukafakg242964926sgfsk
12460vishnusdfsdfsdf
12388vivekgfdg34455gbjg
12072vvvv11bnbn
12354vvvmmm256522bbb
12569vzvcxvxcvxcvcxvcxvcxvcxvx
12788wwww
12560ww12www
13080wwww
13037wwwe
12603wwww
13253watsthe F**is
12421wdwwewewewewewe
12985wer2rerwet24234234234fewrwerwe
13206wertwertwertwert
12179what is this87986283476testcity
12398wqasdasdads
12762wqeqwewqwewqeqwew
12372wqeqbjsbcsjbcnzbcnzxbcNXCBNZBC
13141wqeqweqweqweqweqweqwe
12453wrewerererwer
12537wrrewerwerwewrew
13000wwqweqwqweqwwew
13189wwwww   
12128xcxcvxcvxcv
12811xcxcsdsd
13343xczczcxc
12073xxxx111xx
12832xxxkbnjbkj jkj kj Ccjb SHC
12508xxxxxwwwwwww1ssssssssss
12436xxxxxxxxxxxxxx234234234
13112XYCewrwerwer324324234erwrwerwerwer
12122xzxxxxxxx
13287ytyuuu
12883yujr
12501yaduconocida1212121212sinaloa
12392yasartrichy22
12677yogeshpune9762738402pune
12359yttytytytytytytyyttytytyty
12531yuhhh
13150yuiuiuiYUIUH
13217yuiyuiyuiyuiyuiyyui
12790yuujukhkjhkjhkhjk
12180zahrafghfghfhfghgfhgfhgfhfg
12769ZCXzcZXCZXcXc
13035zdxdssdsd
13036zdxdssdsd
13134zz   
                
// 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 | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/25/2013 2:20:35 PM