|
楼主 |
发表于 2020-7-4 23:45:01
|
显示全部楼层
private DataTable Get_Dt(string sql)
{
String strConnection=ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection myConnection=new SqlConnection(strConnection);
myConnection.Open();
SqlDataAdapter myAdp=new SqlDataAdapter(sql,myConnection);
DataTable myDt = new DataTable();
try
{
//填充数据
myAdp.Fill(myDt);
//返回数据集
return(myDt);
}
catch(OleDbException ex)
{
//显示错误信息
throw ex;
}
finally
{
//关闭数据库连接
myConnection.Close();
}
}
/// <summary>
/// 页面加载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Page_Load(object sender, System.EventArgs e)
{
//接收参数
string sortid = this.Request.QueryString["sortid"];
//判断参数是否为空(注意:空有两种形式,一种为null,一种为空)
if(sortid + "a" != "a")
{
//如果有传递上述参数,则表示联动操作开始
this.xmlBind(sortid);
}
//在页面初次加载的时候,绑定第一/二个下拉框,第二个下拉框为所有值
//但实际上,第二个下拉框应显示空值,因为所有值可能也不少,最好只显示一个"请选择"字样
if(!this.IsPostBack)
{
this.DownBind1();
this.DownBind2();
}
}
/// <summary>
/// 返回第2个下拉框需要的值给xmlhttp
/// </summary>
/// <param name="sortid">传递的关键ID值</param>
private void xmlBind(string sortid)
{
string mystr = "";
string sql = "select typename,typeid from class_2 where sortid = " + sortid ;
DataTable mytab = this.Get_Dt(sql);
//将取到的值形成: ID|名称,ID|名称...这样的形式
if(mytab.Rows.Count != 0)
{
for(int i=0;i<mytab.Rows.Count;i++)
{
mystr += "," + mytab.Rows[i]["typeid"].ToString() + "|" + mytab.Rows[i]["typename"].ToString();
}
mystr = mystr.Substring(1);
}
//输出页面
this.Response.Write(mystr);
this.Response.End();
}
/// <summary>
/// 绑定第一个下拉框
/// </summary>
private void DownBind1()
{
//显示所有的主分类
string sql = "select sortid,sort from class_1 order by sortid asc ";
DataTable mytab = this.Get_Dt(sql);
//绑定第一个下拉框
this.mydown1.DataSource = mytab;
this.mydown1.DataValueField = "sortid";
this.mydown1.DataTextField = "sort";
this.mydown1.DataBind();
//添加一个"请选择"行
this.mydown1.Items.Insert(0,new ListItem("请选择分类",""));
//为此下拉框添加一个默认选择项(此处默认为sortid = 1
//做选项时,如果你添加的选定项而此控件中却没有此项,即会出错
//如:this.mydown1.SelectedValue = "1";
//所以此处以如下方式进行选定
ListItem myItem = this.mydown1.Items.FindByValue("1");
if(myItem != null)
{
myItem.Selected = true;
}
//为此下拉框添加选择事件,第一个参数是自己,第二个参数为要填充的下拉框的名称
this.mydown1.Attributes.Add("onchange","XmlPost(this,'" + this.mydown2.ClientID + "');");
}
/// <summary>
/// 绑定第二个下拉框
/// </summary>
private void DownBind2()
{
//默认显示分类号为1的所有子类
string sql = "select sortid,typename,typeid from class_2 where sortid =1" ;
DataTable mytab = this.Get_Dt(sql);
//绑牢控件
this.mydown2.DataSource = mytab;
this.mydown2.DataSource = mytab;
this.mydown2.DataValueField = "typeid";
this.mydown2.DataTextField = "typename";
this.mydown2.DataBind();
//添加一个空的首行
this.mydown2.Items.Insert(0,new ListItem("请选择名称",""));
}
|
|