2012-03-25

Asp .Net Grid View Databinding Sample

To load the data from Sql server database we can use Ado.Net objects. One of the best object is Sqlclient. So We may include the following namespaces in imports section to call the objects without specifying fully distinguished names, If these name spaces are not used. We may need to call the classes as System.Data.Dataset but since we are going to import the Import System.Data we can plainly call as Dim dsGrid As dataset

Import System.Data Import System.Data.SqlClient

ASP Web Host

Next step is to Get the relationship to the database. Since we have already decided to use the SqlClient. We have to use SqlConnection to open a relationship as follows.

1. Initalize the relationship object Dim ConGrid As New SqlConnection

2. Specify the relationship string ConGrid.ConnectionString = "Server= localhostSqlexpress;Database=Northwind;Trusted_Connection=true"

3. Open the relationship ConGrid.Open()

Note: Northwind database can be obtained from Msdn

Next step is to use the opened relationship to fetch data. We have some options to fetch the data. But in this example I am going to use SqlDataAdapter and DataSet.

1. Initialize the SqlDataAdapter and DataSet

Dim AdaGrid As New SqlDataAdapter

Dim dsGrid As New DataSet

2. Generate a command object

3. Join together the command object with the opened active connectoin

4. Assign the command object to the SqlDataAdapter AdaGrid.SelectCommand = New SqlCommand("select CategoryId, CategoryName, description from Categories", ConGrid)

5. Use SqlDataAdapter's fill formula to fill the dataset

AdaGrid.Fill(dsGrid)

6. Close the connection

ConGrid.Close()

7. Assign the dataset to the GridView's Datasource

GridView1.DataSource = dsGrid.Tables(0)

8. Bind the GridView with Dataset

GridView1.DataBind().

Asp .Net Grid View Databinding Sample

No comments:

Post a Comment