GridView Control Beginners Guide
Author: DevASPTeam
Download Source Code : 712_DatagridSample.zip
In this article I will try to explain you the basics of binding data to GridView Control. Here I have created application using ASP.Net 2.0. This article will be helpful for beginners.
GridView is among the basic control for binding data and displaying data on web form. When ever we fetch record from database we usually prefer gridview control for displaying our data. So here I will cover the basic of it. To begin with application, select GridView control from toolbox from the left pane of Visual studio editor. You will find the gridview control in data control category. Simply drag and drop on your web form. Now set its properties that is, it’s ID=IDs, runat=server and AutoGenerateColumn=false. Add columns using Column tag, add templates using ItemTemplate tag. Your aspx code for your web form will be look like as follows:
Note the headertext property set the text of your column header. DataBinder.Eval(Container.DataItem, "EmpFirstName") this will display text of your EmpFirstName column. Basically this binds your selected column text with control text which is being used for displaying data or it can be used without any control upto user/developer.
Now we come to code behind code. Declare three global objects, first is Connection object, second is Adapter object and last is Dataview object. The namespace used for accessing the sqlconnection and sqldataadapter is System.Data.SqlClient:
Define a Page_Unload event, this event closes the connection and disposes the dataadapter object.
Define a function that returns the dataview object. This object contains the result which is fetched from the database using sqldataadapter:
Now the last task left is binding the result to gridview control. On page load check the IsPostback property and on false bind the result (IsPostback property checks the page Postback event).
this.Page.Unload defines the Unload event. “dv.Sort” sorts the record with respect the “empfirstname” column record. You can add more then one column it works same as Order By clause usually used in select query.