简单的通过连接数据库给下拉菜单赋值(DropDownList)

来源:互联网 发布:淘宝网t恤女装长袖 编辑:程序博客网 时间:2024/05/21 09:21

protected void Page_Load(object sender, EventArgs e) 
    { 
        if (!IsPostBack) 
        { 
            SqlConnection con = new SqlConnection("server=;database=province;uid=sa;pwd=sa;"); 
            con.Open(); 
            SqlCommand cmd = new SqlCommand("select * from province", con); 
            SqlDataReader sdr = cmd.ExecuteReader(); 
            DropDownList1.DataSource = sdr; 
            DropDownList1.DataTextField = "proname"; 
            DropDownList1.DataValueField = "proid"; 
            DropDownList1.DataBind(); 
            con.Close(); 
            sdr.Close(); 
        } 
        
        
    } 
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
      
            SqlConnection con = new SqlConnection("server=;database=province;uid=sa;pwd=sa;"); 
            con.Open(); 
            SqlCommand cmd2 = new SqlCommand("select * from city where proid=" + DropDownList1.SelectedValue, con); 
            SqlDataReader sdr2 = cmd2.ExecuteReader(); 
            DropDownList2.DataSource = sdr2; 
            DropDownList2.DataTextField = "cityname"; 
            DropDownList2.DataValueField = "cityid"; 
            DropDownList2.DataBind(); 
            DropDownList2.Visible = true; 
            sdr2.Close(); 
            con.Close(); 
        
    } 

 

 

前台:
<td class="td_page">新闻类型:</td>
<td><asp:DropDownList ID="dropNewType" runat="server"></asp:DropDownList></td>
 
后台:
DataTable dt = CDB.FillTable("select TypeId, TypeContent from [newsTypeTable]");
dropNewType.DataSource = dt;
dropNewType.DataTextField = "typeContent";
dropNewType.DataValueField = "TypeId";
dropNewType.DataBind();