关于网友提出的“dropdownlist 绑定 DropDownList 怎么绑定数据?后台自己写的绑定。”问题疑问,本网通过在网上对“dropdownlist 绑定 DropDownList 怎么绑定数据?后台自己写的绑定。”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题:dropdownlist 绑定 DropDownList 怎么绑定数据?后台自己写的绑定。
描述:
这个是前台页面的代码。
//这个是SQL语句
select names from Userinfo where names='"+names+"' order by id desc
怎么绑定呢?哪个碰能帮我写下..
DropDownList1.DataTextField = "ItemName"; //dropdownlist的Text的字段
DropDownList1.DataValueField = "id";//dropdownlist的Value的字段
这2行代码,老是理解不到
解决方案1: DropDownList1.DataTextField = "ItemName"; //dropdownlist的Text的字段
就是显示的字段
DropDownList1.DataValueField = "id";//dropdownlist的Value的字段
显示字段对应的值
this.DropDownList1.SelectedValue;的时候取的是这个值
select names from Userinfo where names='"+names+"' order by id desc
里取2个字段呗
protected void Page_Load(object sender, EventArgs e)
{
string sql = "select * from Userinfo where names='" + names + "' order by id desc";
this.DropDownList1.DataSource = ReturnDataTable(sql);
this.DropDownList1.DataTextField = "显示的字段";
this.DropDownList1.DataValueField = "值的字段";//2个字段在DataTable里都包含
this.DropDownList1.DataBind();
}
public static DataTable ReturnDataTable(string cmdtext)
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "数据库连接字符串";
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand(cmdtext, cn);
cmd.CommandType = CommandType.Text; ;
SqlDataReader dr = null;
using (dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
dt.Load(dr);
}
return dt;
}
最后加个请选择
this.DropDownList1.Items.Insert(0, new ListItem("请选择", ""));
以上介绍了“dropdownlist 绑定 DropDownList 怎么绑定数据?后台自己写的绑定。”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/2181392.html