江湖救急:如何让 DropDownList 绑定到不同的数据源?
在数据库中有几张表,我想实现这样一个功能:通过选择不同的表名,让一个DropDownList从被选择的表中读取数据作为它的数据项,这可不可以实现啊?我查MSDN查了半天也没查到,请各位高手大侠教教小弟啊。谢谢了!
------解决方案--------------------可以,就是表名是不能做参数的,需要拼接字符串
------解决方案--------------------不同的databind()或者让数据源使用不同的sql语句不能解决么?
------解决方案--------------------服务器端判断选择的参数==>转化成相应的SQL==>选取数据==>绑定
------解决方案--------------------//aspx
<form id= "form1 " runat= "server ">
<div>
<asp:TextBox ID= "TextBox1 " runat= "server "> </asp:TextBox>
<asp:Button ID= "Button1 " runat= "server " Text= "Button " OnClick= "Button1_Click " /> <br />
<asp:DropDownList ID= "DropDownList1 " runat= "server ">
</asp:DropDownList> </div>
</form>
//aspx.cs
private void BindDropDownList(string strTable)
{
SqlConnection cn = new SqlConnection(@ "server=.\SQLExpress;uid=sa;pwd=sa;database=pubs ");
string strSQL = string.Empty;
if (strTable == string.Empty)
strSQL = "select * from authors ";
else
strSQL = "select * from " + strTable;
SqlCommand cmd = new SqlCommand(strSQL, cn);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
DropDownList1.DataSource = dr;
DropDownList1.DataTextField = dr.GetName(0);
DropDownList1.DataValueField = dr.GetName(1);
DropDownList1.DataBind();
dr.Close();
cn.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList(string.Empty);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
BindDropDownList(TextBox1.Text);
}
------解决方案--------------------public void DropDownListBind(string tablename, string text, string value)
{
string sql=string.Format( "select * from {0} ",tablename);
DropDownList1.DataSource = DbHelp.Query(sql).Tables[0];
DropDownList1.DataTextField = text;
DropDownList1.DataValueField = value;
DropDownList1.DataBind();
}