Datasheet
lstCategory.DataValueField = "CategoryID";
lstCategory.DataTextField = "CategoryName";
lstCategory.DataBind();
}
}
When the Fetch button is clicked, we need to get the value from the DropDownList. For this, we use the
SelectedValue property, which is new to ASP.NET 1.1. This contains the ID of the selected category,
and we pass this into the
GetProducts routine, which will return a DataSet of the products.
However, we can't pass this value directly into
GetProducts as an integer value is expected, and the
SelectedValue returns a string. So we have to convert it first using the ToInt32 method of the
Convert class. This is a static class method (which doesn't require an instance of the Convert class) and
simply takes a single string argument. The return value from
ToInt32 is an integer representation of the
string passed in.
The
DataSet returned from GetProducts is set to the DataSource of the grid and the DataBind
method is called to bind the data:
void Button1_Click(object sender, EventArgs e) {
DataGrid1.DataSource =
GetProducts(Convert.ToInt32(lstCategory.SelectedValue));
DataGrid1.DataBind();
}
There are two routines to fetch data, but one of them is the same as we've already seen – using a simple
DataSet to fetch data (in this case the Categories). What we want to see is the GetProducts routine,
which gets filtered data. The first thing to notice is that it accepts an
int argument – this will contain the
CategoryID, passed in from the button click event:
System.Data.DataSet GetProducts(int categoryID) {
Next, we define the connection details, as we've seen in previous examples:
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " +
"Ole DB Services=-4; Data Source=C:\\BegASPNET11\\" +
"data\\Northwind.mdb";
System.Data.IDbConnection dbConnection =
new System.Data.OleDb.OleDbConnection(connectionString);
Then we define the query:
string queryString = "SELECT [Products].[ProductName], "
"[Products].[QuantityPerUnit], [Products].[UnitPrice],"+
"[Products].[UnitsInStock] FROM [Products] " +
"WHERE ([Products].[CategoryID] = @CategoryID)";
Note that the WHERE clause is filtering on CategoryID. However, the value used for the filter
(
@CategoryID) is not a real value but a placeholder. This tells ADO.NET that the value will be supplied
by a parameter.
276
Chapter 8
57084_08.qxp 30/01/2004 8:03 PM Page 276