日期:2011-04-15  浏览次数:20480 次

In Part 1 we looked at how to bind a DataReader to a radio button list, but how do we respond to the user's choice? In this part we'll look at how to display a list of books for the particular publisher the user selected from the databound radio button list!

Responding to a User's Radio Button Choice
What we'd like to accomplish is to allow the user to choose a radio button option, click a button, and have the chosen publisher's books appear. So, to accomplish this, we'll need to first add a button control after the radio button list control in our HTML section:

<html>
<body>
  <form runat="server">
    <b>Choose a Publisher's Books to View</b><br>
    <asp:radiobuttonlist id="radlstPubs" runat="server"
             DataValueField="PublisherID" DataTextField="Name" />
    <br>
    <asp:button id="btnViewBooks" runat="server"
             Text="View Published Books" OnClick="btnViewBooks_Click" />
  </form>
</body>
</html>




Note that the btnViewBooks button control's OnClick event handler was wired up to the btnViewBooks_Click event handler. This is an event handler that we'll create in our server-side script block. This event handler will need to ascertain what radio button option was selected and construct a SQL query based upon that information. (This SQL query will snag all of the books out of the tblBooks table whose PublisherID matches the ID of the selected publisher from the radio button list.) Furthermore, a DataReader (or DataSet) should be populated with the results of this custom SQL query, and that DataReader should be bound to a DataGrid Web control in order to display the books for the publisher.

So, we'll need one more Web control, a DataGrid, which will be used to display the books published by the selected publisher. The DataGrid Web control I used can be seen below, it should come after the button control (which has been removed for brevity). Feel free to make any stylistic changes to the DataGrid:

<html>
<body>
  <form runat="server">
    ... CONTENT REMOVED FOR BREVITY ...
    
    <p align="center">
    <asp:label id="lblTitle" runat="server" Font-Name="Verdana"
          Font-Size="Large" Font-Bold="True" />

    <asp:datagrid id="dgBooks" runat="server"
      Font-Name="Verdana" Font-Size="Smaller"
      HeaderStyle-BackColor="Purple" HeaderStyle-ForeColor="White"
      HeaderStyle-Font-Size="Small" HeaderStyle-Font-Bold="True"
      AutoGenerateColumns="False">
    
      <Columns>
      
        <asp:BoundColumn HeaderText="Book Title"
                HeaderStyle-HorizontalAlign="Center"
                DataField="Title" />
 &