dropdownlist的使用以及默认文本自定义

我们经常会用到下拉框dropdownlist
下面附上使用代码
前端(工具箱直接拖进来即可)

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList>

后端
代码一定要写在整体程序Page_Load下,不要写在DropDownList1_SelectedIndexChanged(我当时就是傻了写在后者里了,嘤嘤嘤)

 protected void Page_Load(object sender, EventArgs e)
        {
            string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            string queryRecord;
            queryRecord = "SELECT hosname FROM hospital_log ";
            SqlCommand com;
            com = new SqlCommand(queryRecord, conn);
            SqlDataReader sqlreader;
            sqlreader = com.ExecuteReader();
            this.DropDownList1.DataSource = sqlreader;
            this.DropDownList1.DataTextField = "hosname";
            this.DropDownList1.DataValueField = "hosname";
            this.DropDownList1.DataBind();
            this.DropDownList1.Items.Insert(0, new ListItem("<--请选择-->", ""));
            sqlreader.Close();
        }

前面的连接数据库代码可见之前博客
拜拜
如若要2个以上dropdownlist进行互联可见两个dropdownlist互联

猜你喜欢

转载自blog.csdn.net/qq_44725217/article/details/106879553