您的位置:首页 > 编程语言 > C#

C#下实现主从DropDownList互动的方法

2005-11-15 17:03 726 查看
C#下实现主从DropDownList互动的方法
作者: 未知
日期:

相信和我一样,有很多同行都遇到主从dropdownlist互动的问题,比如选择了县,那么让系统自动在dropdownlist2中列出该县下属的乡名列表,而选了乡后,再在dropdownlist3中列出该乡下属的村的列表,那么我以前的解决方法是重新Rill相应dropdownlist所绑定的dataset,这样费事费资源,而且麻烦,其实我们可以用RowFilter来实现,下面是我的具体实现方法:
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
InitA();//该方法不能放置在Page_Load下 不管是否IsPostBack;
}
//初始化dorpdownlist
DataSet Myds;
//CConection 为我的自定义类;实现与数据库的连接,其中有一属性为cnn,为OleDbConnection.
CConection Mycnn;
public void InitA()//可以为private void InitA()
{
Mycnn=new CConection();
string strSql;
strSql="select 编号,名称 from sys_county order by 编号";
OleDbDataAdapter MyoleAp=new OleDbDataAdapter(strSql,Mycnn.Cnn) ;
Myds=new DataSet() ;
MyoleAp.Fill(Myds,"sys_county");
this.DropDownList1.DataSource=Myds.Tables["sys_county"];
this.DropDownList1.DataValueField="编号";
this.DropDownList1.DataTextField="名称";
this.DropDownList1.DataBind();
strSql="select 编号,名称,所属县 from sys_town order by 编号";
MyoleAp.SelectCommand.CommandText=strSql;
MyoleAp.Fill(Myds,"sys_town");
this.DropDownList2.DataSource=Myds.Tables["sys_town"];//必须指定Table 比如myds.Tables[0];
this.DropDownList2.DataValueField="编号";
this.DropDownList2.DataTextField="名称";//这里也可以初始化绑定全部 this.DropDownList2.DataBind();
MyoleAp.Dispose();
}
//DropDownList1的changed改变dorpdownlist2的显示值,
private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
Myds.Tables["sys_town"].DefaultView.RowFilter="所属县='" + this.DropDownList1.SelectedValue +"'";
this.DropDownList2.DataBind();
}
[注意:]以上代码在C#的webform下实现,dropdownlist1的autopostback必须为true.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: