This walkthrough shows you how to Bind WebGrid to a DataSource at RunTime.
During this walkthrough, you will learn how to do the following:
- Connect to a Microsoft Access database using Microsoft Jet 4.0 OLE DB Provider.
- Use OleDbDataAdapter to configure SQL Query and generate DataSet.
- Set Web Application's environment and the DataSource.
- Create DataSet.
- 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 Microsoft Access Northwind database.
- Visual Studio 2005 Application.
Step-By-Step Instructions
To Bind DataSource in WebGrid at RunTime.
- 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 DataSet inside the code-behind under the namespace then paste in the codes below:
C# Copy Code public DataSet LoadData() { OleDbCommand cmd = oleDbConnection1.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM CUSTOMERS"; OleDbDataAdapter da = newOleDbDataAdapter(); da.SelectCommand = cmd; DataSet ds = new DataSet(); da.Fill(ds); ds.Tables[0].TableName = "Customers"; return ds; }
-
Double click the WebGrid and add following codes inside the 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.