首页 > 开发 > 综合 > 正文

DataGrid学习三

2024-07-21 02:22:37
字体:
来源:转载
供稿:网友
上一例中静态填充选择框的值,但这不太适合那些值在数据库中会更改的情况。因为 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 >
  <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>
上一篇:DataGrid学习四

下一篇:DataGrid学习二

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表