在一个Form里同时使用两个SelectionList时遇到了问题,我想实现如下功能:
就是两个控件都是绑定数据的,而第二个控件的数据是要根据第一个控件选择后而改变的,我应该用什么属性或事件?或者怎么做?
如果我第一个控件的内容为省份,而第二个控件的内容为城市。
在第一个下拉框,设定它的autopostback=true,启用它的选择事件,详细如下:
//前台写法
<form id="Form1" method="post" runat="server">
<asp:DropDownList id="DropDownList1" runat="server" AutoPostBack="True"></asp:DropDownList>
<asp:DropDownList id="DropDownList2" runat="server"></asp:DropDownList>
</form>
//后台写法示例
//定义数据库连接串
private System.Data.OleDb.OleDbConnection conn;
/// <summary>
/// 打开MDB数据连接
/// </summary>
private void openMdb()
{
string mdbPath = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + this.Server.MapPath("data.mdb");
this.conn = new System.Data.OleDb.OleDbConnection(mdbPath);
this.conn.Open();
}
/// <summary>
/// 关闭数据库对象
/// </summary>
private void conn_close()
{
this.conn.Close();
}
/// <summary>
/// 返回DATATABLE对象
/// </summary>
/// <param name="sql">要求取的SQL语句</param>
/// <returns>返回DataTable对象</returns>
private DataTable GetDt(string sql)
{
openMdb();
OleDbDataAdapter myAdp = new OleDbDataAdapter (sql, this.conn);
DataTable dt = new DataTable();
try
{
myAdp.Fill(dt);
}
catch (Exception ex)
{
this.Response.Write(ex.Message);
}
conn_close();
return(dt);
}
private void Page_Load(object sender, System.EventArgs e)
{
if(!this.IsPostBack)
{
string sql = "select sid,sname from table ";
DataTable myTab = this.GetDt(sql);
this.DropDownList1.DataSource = myTab;
this.DropDownList1.DataValueField = "sid";
this.DropDownList1.DataTextField = "sname";
this.DropDownList1.DataBind();
}
}
/// <summary>
/// 下拉框事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
string myKeyid = this.DropDownList1.SelectedValue;
if(this.DropDownList1.SelectedValue != "")
{
string sql = "select sid,sname from table where 省份 = " + myKeyid ;
DataTable myTab = this.GetDt(sql);
this.DropDownList2.DataSource = myTab;
this.DropDownList2.DataValueField = "sid";
this.DropDownList2.DataTextField = "sname";
this.DropDownList2.DataBind();
}
}
站长评论:其他对于懂ASP。NET的开发WEB的程序员来说这个问题不算什么?其他是WEB开发一样,只要是处理SelectedIndexChanged事件 另外要把相对的属性设置好 比如AUTOPOSTBACK