日期:2008-11-16  浏览次数:20593 次

上一例中静态填充选择框的值,但这不太适合那些值在数据库中会更改的情况。因为 select HtmlControl 也支持 IEnumerable



DataSource 属性,可以转而使用选择查询动态填充选择框,这将保证数据库和用户界面始终同步。下面的示例说明此过程。



<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>



<html>
<script language="C#" runat="server">
    SqlConnection myConnection;
    protected void Page_Load(Object Src, EventArgs E)
    {
       myConnection = new SqlConnection("user id=sa;password=;initial catalog=pubs;data source=jeff");        
        if (!IsPostBack)
        {
            SqlDataAdapter myCommand = new SqlDataAdapter("select distinct State from Authors", myConnection);
            DataSet ds = new DataSet();
            myCommand.Fill(ds, "States");
            MySelect.DataSource= ds.Tables["States"].DefaultView;
            MySelect.DataBind();
        }
    }



    public void GetAuthors_Click(Object sender, EventArgs E)
    {
        String selectCmd = "select * from Authors where state = @State";       
        SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection);
        myCommand.SelectCommand.Parameters.Add(new SqlParameter("@State", SqlDbType.NVarChar, 2));
        myCommand.SelectCommand.Parameters["@State"].Value = MySelect.Value;
        DataSet ds = new DataSet();
        myCommand.Fill(ds, "Authors");
        MyDataGrid.DataSource= ds.Tables["Authors"].DefaultView;
        MyDataGrid.DataBind();
    }



</script>



<body style="font: 10.5pt 宋体">
  <form runat="server">
    <h3><font face="宋体">对 DataGrid 控件的动态参数化选择</font></h3>
    选择州:
    <select id="MySelect" DataTextField="State" runat="server"/>
    <input type="submit" OnServerClick="GetAuthors_Click" Value="获取作者" runat="server"/><p>
    <ASP:DataGrid id="MyDataGrid" runat="server"
      Width="700"
      BackColor="#ccccff"
      BorderColor="black"
      ShowFooter="false"
      CellPadding=3
      CellSpacing="0"
      Font-Name="宋体"
      Font-Size="8pt"
      HeaderStyle-BackColor="#aaaadd"
      EnableViewState="false"
    />
  </form>
</body>
</html>