如何使用dropdownlist绑定数据库?我们需要了解dropdownlist的一些属性。
DataSource:为数据源
DataBind:数据源绑定
DataTextField:要显示的文本值
DataValueField:显示文本值的编号
其中DataTextField主要是给用户看的,我们程序员要用的是DataValueField。
一、C#程序添加如下命名空间
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;
二、编写方法,返回DataTable
static string ConnStr = "Server=localhost;UserId=root;Password=12345678;Database=reservoirinfo;pooling=false;CharSet=utf8;port=3306";//声明一个字符串用来存放连接数据库的信息
public static DataTable Table(string sql)
{
using (MySqlConnection conn = new MySqlConnection(ConnStr))
{
MySqlDataAdapter sda = new MySqlDataAdapter(sql, conn);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
三、数据库reservoirinfo的表名为table1,包含2个字段:id和name
四、DropDownList绑定数据库的id字段和name字段
id字段提供给程序员,name字段给用户查看选择。
protected void Page_Load(object sender, EventArgs e)
{
string sql = string.Format(" select * from table1");
DropDownList1.DataSource = Table(sql);
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "id";
DropDownList1.DataBind();
}
五、前台程序代码
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" style="z-index: 1; left: 287px; top: 95px; position: absolute; height: 22px; width: 235px">
</asp:DropDownList>
六、运行效果
七、如何获得我选中的那一项的ID值
int id=int.Parse(this.DropDownList1.SelectedItem.Value);