asp.net(C#)的DropDownList控件怎么数据绑定

2025-02-06 12:11:12
推荐回答(2个)
回答1:

DataTable df = DBUtility.DbHelperSQL.Query(ff).Tables[0]; //查表tb_Teacher
DataTable dt1 = new DataTable();
dt1.Columns.Add("id");
dt1.Columns.Add("name");
for (int i = 0; i < df.Rows.Count; i++)//遍历所有行,查tb_Classag表中 id=id

{
string sa2 = "select * from tb_Classag where id=" + Convert.ToInt32(df.Rows[i]["id"]);
DataTable ds = DBUtility.DbHelperSQL.Query(sa2).Tables[0];
if (ds.Rows.Count > 0)//如果查到,添加到dt1
{

dt1.Rows.Add(Int32.Parse(ds.Rows[0]["id"].ToString()), ds.Rows[0]["name"]);

}

}
DropDownList3.DataSource = dt1; //DropDownList3 绑带数据,显示 DropDownList3.DataTextField = "name"; //文本内容字段
DropDownList3.DataValueField = "id"; //值字段
DropDownList3.DataBind();

回答2:

你这样写绑定不上吗?
查询出来dt 而后循环dt foreach(Datarow dr in dt)

this.ddl.itmes.add(new listitem(dr[].tostring(),dr[].tostring()));// 文本和值