Datasheet
13. Save the file and run it.
14. Select a category and then click Fetch to see only the products for that category shown in Figure
8-22:
Figure 8-22
What you've achieved here is two things. First, you've used two controls that are bound to data – the list
of categories and the grid of products. Second, you only fetched the products for a selected
category – you've filtered the list. Let's see how this works.
How It Works
Let's start the code examination with the Page_Load() event, where we fill the Categories list:
void Page_Load(Object Sender, EventArgs e) {
We only want to fetch the data and bind it to the list the first time the page is loaded, so we use the
IsPostBack property of the page to check if this is a postback. If it isn't, it must be the first load, so we
fetch the data. We don't need to do this on subsequent page requests as the list itself stores the data.
if (!Page.IsPostBack) {
lstCategory.DataSource = GetCategories();
Instead of calling the DataBind straight away, we want to tell the list which columns from the data to
use. A
DropDownList stores two pieces of information – one is shown on the page (the text field), and
the other is hidden (the value field). The text field is used for what the user needs to see, while the value
field often contains an ID – what the user doesn't need to see. The
DropDownList doesn't automatically
know which columns contain these pieces of information, thus we use the
DataValueField and
DataTextField properties. The DataValueField is the CategoryID, the unique key for the category,
and this will be used later in our code:
275
Reading from Databases
57084_08.qxp 30/01/2004 8:03 PM Page 275