This walkthrough shows you how to bind a SQL Server 2000 Tables to WebGrid.
During this walkthrough, you will learn how to do the following:
- Connect to a Microsoft SQL Server 2000 database.
- Set Web Application's environment and the DataSource.
- Create SQL Server 2000 DataSet and relations between the table.
- Use WebGrid's InitializeDataSource event to bind the DataSet.
- Use WebGrid's PrepareDataBinding event to retrieve structure in WebGrid.
Prerequisites
In order to complete this walkthrough, you will need the following:
- Access to the SQL Server 2000 database.
- Visual Studio 2005 Application.
Step-By-Step Instructions
To Bind SQL Server 2000 Tables in WebGrid.
- Launch Visual Studio.NET 2005.
- Click on File menu, then select New and click Project.
- Select Visual C# Project in Project Types.
- Select ASP.NET Web Application in the Template box.
- Specify the Project's Location and click OK.
- Drag WebGrid into WebForm.
- Add following class inside the code-behind under the namespace then paste in the codes below:
C# Copy Code DataSet ds = new DataSet(); string connString = "workstation id=DEVELOPER2;packet size=4096;user id=sa;data source=DEVELOPER2;persist security info=False;initial catalog=Northwind"; SqlConnection conn = new SqlConnection(connString); SqlDataAdapter daCustomers = new SqlDataAdapter(); string queryCustomers = "SELECT * FROM Customers"; daCustomers.SelectCommand = new SqlCommand(queryCustomers, conn); daCustomers.Fill(ds, "Customers"); SqlDataAdapter daOrders = new SqlDataAdapter(); string queryOrders = "SELECT * FROM Orders"; daOrders.SelectCommand = new SqlCommand(queryOrders, conn); daOrders.Fill(ds, "Orders"); SqlDataAdapter daOrderDetails = new SqlDataAdapter(); string queryOrderDetails = "SELECT * FROM [Order Details]"; daOrderDetails.SelectCommand = new SqlCommand(queryOrderDetails, conn); daOrderDetails.Fill(ds, "Order_Details"); DataRelation drCusOrd = new DataRelation("CustOrd", ds.Tables["Customers"].Columns["CustomerID"], ds.Tables["Orders"].Columns["CustomerID"] ); DataRelation drOrdOrdDetails = new DataRelation("OrdOrdDet", ds.Tables["Orders"].Columns["OrderID"], ds.Tables["Order_Details"].Columns["OrderID"] ); ds.Relations.Add(drCusOrd); ds.Relations.Add(drOrdOrdDetails); return ds; }
-
Double click the WebGrid and add the following codes under InitializeDataSource event handler:
C# Copy Code e.DataSource = LoadData();
- Then, it will automatically retrieve its structure by using RetrieveStructure() method in PrepareDataBinding event handler:
C# Copy Code if(!IsPostBack) { WebGrid1.RetrieveStructure(); }
- Compile and run the WebForm.