DropdownList绑定的两种方法,下实现主从DropDownList互动的方法
分类:高并发

相信和我一样,有很多同行都遇到主从dropdownlist互动的问题,比如选择了县,那么让系统自动在dropdownlist2中列出该县下属的乡名列表,而选了乡后,再在dropdownlist3中列出该乡下属的村的列表,那么我以前的解决方法是重新Rill相应dropdownlist所绑定的dataset,这样费事费资源,而且麻烦,其实我们可以用RowFilter来实现,下面是我的具体实现方法:

动态绑定方法一:动态绑定数据库中的字段。

                                                                                             省市联动下拉菜单的实现
一、数据库的建立
为了更好的实现与数据库连接,省表中需要有两个元素,一个是省编号,一个是省名称;市表中需要有三个元素,一个是市编号,一个是市名称,更重要的是这个市改隶属于那个省。
省表(UserProvince)
ProID    ProName
1            河南
2            安徽
市表(UserCity)
CityID    ProID    CityName
1              1         郑州
2              2         合肥

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TeachPlat.templatecontrol;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web.SessionState;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient ;
using System.Configuration;
using System.IO;

override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
InitA();
}

SqlConnection conn = UtilitySqlClass.OperateDataBase.ReturnConn(); string strSQL = "select * from CompanyType"; SqlDataAdapter ada = new SqlDataAdapter(strSQL, conn); DataSet ds = new DataSet(); ada.Fill(ds, "CompanyType"); DropDownList1.DataSource = ds.Tables["CompanyType"].DefaultView; DropDownList1.DataValueField = ds.Tables["CompanyType"].Columns[1].ColumnName; DropDownList1.DataTextField = ds.Tables["CompanyType"].Columns[1].ColumnName; DropDownList1.DataBind(); ds.Dispose();

二、代码
后台:(定义两个关于省市的的函数,通过SelectedIndexChanged事件实现对市的筛选)
protected void Page_Load(object sender, EventArgs e)
    {
            BindProvince();
            BindCity();
        }
 private void BindProvince()
        {
            string sql = "select ProID,ProName from UserProvince";
            SqlConnection conn = new SqlConnection("SqlDataSource1");
            SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
            DataSet ds = new DataSet();
            conn.Open();
            adapter.Fill(ds);
            conn.Close();
            ddlprovince.DataSource = ds.Tables[0];
            ddlprovince.DataValueField = "ProID";
            ddlprovince.DataTextField = "ProName";
            ddlprovince.DataBind();
        }
        private void BindCity()
        {
            string sql = "select CityID,ProID,CityName from UserCity; ";
            SqlConnection conn = new SqlConnection("SqlDataSource2");
            SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
            DataSet ds = new DataSet();
            conn.Open();
            adapter.Fill(ds);
            conn.Close();
            ddlCity.DataSource = ds.Tables[0];
            ddlCity.DataValueField = "CityID";
            ddlCity.DataTextField = "CityName";
            ddlCity.DataBind();
        }
protected void ddlprovince_SelectedIndexChanged(object sender, EventArgs e)
    {
       
            int ProID = this.ddlprovince.SelectedIndex + 1;
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = "User ID=sa;Initial Catalog=News;Data Source= (local);Password=123";
            conn.Open();
            SqlCommand cmd = new SqlCommand("select * from [News].[dbo].[UserCity] where ProID='"+ProID+"'");
            cmd.Connection = conn;
            SqlDataReader sdr = cmd.ExecuteReader();
            //绑定
            this.ddlCity.DataSource = sdr;
            this.ddlCity.DataTextField = "CityName";
            this.ddlCity.DataValueField = "CityID";
            this.ddlCity.DataBind();
            sdr.Close();
            conn.Close();
        }
}
前台:(两个连接数据库的DropDownList控件)
 <asp:DropDownList ID="ddlprovince" runat="server" widtn="55px" DataSourceID="SqlDataSource1" DataTextField="proName" DataValueField="proID" AutoPostBack="True" OnSelectedIndexChanged="ddlprovince_SelectedIndexChanged">
                                    </asp:DropDownList>
                                    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NewsConnectionString2 %>" SelectCommand="SELECT [proID], [proName] FROM [Userprovince]"></asp:SqlDataSource>
                                    <asp:DropDownList ID="ddlCity" runat="server" widtn="55px"  DataTextField="cityName" DataValueField="cityID" AutoPostBack="True">
                                    </asp:DropDownList>
                                    <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:NewsConnectionString3 %>" SelectCommand="SELECT [cityID], [proID], [cityName] FROM [UserCity]"></asp:SqlDataSource>

namespace TeachPlat.Controls
{
 /// <summary>
 /// news 的摘要说明。
 /// </summary>
 
 public class add_news: TemplatedWebControl
 {
  protected SqlDataReader dr;
  protected SqlCommand mycmd;
  protected SqlDataAdapter da;
  protected DataSet ds;
  DropDownList DropDownList1;
  DropDownList DropDownList2;
  SqlConnection Con=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]); 
  TextBox TextBox3;
  TextBox TextBox4;
  TextBox TextBox5;
  TextBox TextBox6;
  Button  Button1;
  Button  Button2;
  DataGrid DataGrid1;
  Label lblID;
  public add_news()
  {
  }
  public int dr2
  {
   get
   {
    this.EnsureChildControls();
    return Int32.Parse(DropDownList1.SelectedItem.Value);
   }
   set
   {
    this.EnsureChildControls();
    DropDownList1.SelectedItem.Value = value.ToString();
   }
  }
  void show_datagrid()
  {
   mycmd=new SqlCommand("select * from News_table",Con);
   da = new SqlDataAdapter(mycmd);
   ds =new DataSet();
   da.Fill(ds, "News_table");
   DataGrid1.DataSource = ds.Tables["News_table"].DefaultView;
   DataGrid1.DataBind();
  }
  void show_dropdownlist1()
  {
   mycmd=new SqlCommand("select * from Text_Type",Con);
   da = new SqlDataAdapter(mycmd);
   ds =new DataSet();
   da.Fill(ds, "Text_Type");
   DropDownList1.DataSource = ds.Tables["Text_Type"].DefaultView;
   DropDownList1.DataTextField = ds.Tables["Text_Type"].Columns["Text_Type"].ToString();
   DropDownList1.DataBind();
  }
  void show_dropdownlist2()
  {
   mycmd=new SqlCommand("select * from Publish_dept",Con);
   da = new SqlDataAdapter(mycmd);
   ds =new DataSet();
   da.Fill(ds, "Publish_dept");
   DropDownList2.DataSource = ds.Tables["Publish_dept"].DefaultView;
   DropDownList2.DataTextField = ds.Tables["Publish_dept"].Columns["Publish_dept"].ToString();
   DropDownList2.DataBind();
  }
  protected override void AttachChildControls()
  {
   lblID=(Label)FindControl("lblID");
   TextBox3=(TextBox)FindControl("TextBox3");
   TextBox4=(TextBox)FindControl("TextBox4");
   TextBox5=(TextBox)FindControl("TextBox5");
   TextBox6=(TextBox)FindControl("TextBox6");
   DataGrid1=(DataGrid)FindControl("DataGrid1");
      DataGrid1.PageIndexChanged+=new DataGridPageChangedEventHandler(DataGrid1_PageIndexChanged);
   DataGrid1.ItemCommand+=new DataGridCommandEventHandler(DataGrid1_ItemCommand);
   DropDownList1=(DropDownList)FindControl("DropDownList1");
   DropDownList2=(DropDownList)FindControl("DropDownList2");
   Button1=(Button)FindControl("Button1");
   Button1.Click+=new EventHandler(Button1_Click);
   Button2=(Button)FindControl("Button2");
   Button2.Click+=new EventHandler(Button2_Click);
   show_dropdownlist1();
   show_dropdownlist2();
   show_datagrid();
  }
  private void Button1_Click(object src ,EventArgs e)
  {
   if(Button1.Text=="确 定")
   {
    mycmd=new SqlCommand("Insert into News_table (News_title,Text_content,Keyword,Publisher,Publishtime,Text_Type,Publish_dept) values('"+TextBox4.Text+"' ,'"+TextBox5.Text+"','"+TextBox6.Text+"','"+TextBox3.Text+"','"+System.DateTime.Now +"','"+DropDownList1.SelectedValue +"','"+DropDownList2.SelectedValue +"')",Con);
       Con.Open();
       mycmd.ExecuteReader();
       Con.Close();
       show_datagrid();
       TextBox3.Text ="";
       TextBox4.Text="";
       TextBox5.Text="";
       TextBox6.Text="";
   }
   else if(Button1.Text=="修 改")
   {
    SqlConnection Con=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]); 
    Con.Open();
    string MySQL;
    MySQL = "Update News_table Set News_title = '"+TextBox4.Text+"', Text_content ='"+TextBox5.Text+"',Keyword ='"+TextBox6.Text+"',Publisher='"+TextBox3.Text+"',Publishtime= '"+System.DateTime.Now +"',Text_Type='"+DropDownList1.SelectedValue +"',Publish_dept='"+DropDownList2.SelectedValue +"' Where News_id ="+ int.Parse(lblID.Text) +"";
                mycmd=new SqlCommand(MySQL,Con);
                mycmd.ExecuteNonQuery();
    Con.Close();
    show_datagrid();
    TextBox3.Text ="";
     TextBox4.Text="";
     TextBox5.Text="";
     TextBox6.Text="";
        Button1.Text="确 定";
   }
   //   HttpContext.Current.Response.Write( "jljljlj" );
  }
  private void Button2_Click(object src ,EventArgs e )
  {
  } 
  private void DataGrid1_ItemCommand( Object source,DataGridCommandEventArgs e)
  
  {   
   if( e.CommandName=="Delete") 
   {
    SqlConnection Con=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]); 
    Con.Open();
    int x;
    x =int.Parse(DataGrid1.DataKeys[e.Item.ItemIndex].ToString()) ;
    mycmd=new SqlCommand("Delete From News_table Where News_id = "+x+"", Con);
    mycmd.Connection = Con;
    mycmd.ExecuteNonQuery();
    Con.Close();
    show_datagrid();
   }
   else if(e.CommandName=="Edit")
   {
    Button1.Text="修 改";
    SqlConnection Con=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]); 
    Con.Open();
    int tempid = int.Parse(DataGrid1.DataKeys[e.Item.ItemIndex].ToString()) ;
    mycmd=new SqlCommand("select * from News_table Where News_id = "+tempid+"",Con);
    dr=mycmd.ExecuteReader();
    while(dr.Read())
    {
     TextBox4.Text =dr[1].ToString();
     TextBox3.Text=dr[3].ToString();
     TextBox5.Text=dr[5].ToString();
     TextBox6.Text=dr[4].ToString();
     DropDownList1.SelectedValue=dr[6].ToString();
     DropDownList2.SelectedValue=dr[7].ToString();
        lblID.Text=dr[0].ToString();
    }
         }
        }
  private void DataGrid1_PageIndexChanged(Object source, DataGridPageChangedEventArgs e)
  {
  DataGrid1.CurrentPageIndex = e.NewPageIndex;
        show_datagrid();
       
  }
  
 }
}

//初始化dorpdownlist

动态绑定方法二:利用DropDownList.Items.Add方法。

DataSet Myds;
//CConection 为我的自定义类;实现与数据库的连接,其中有一属性为cnn,为OleDbConnection.
CConection Mycnn;

protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { SqlConnection conn = UtilitySqlClass.OperateDataBase.ReturnConn(); try { conn.Open(); this.DropDownList1.Items.Add; string strSQL = "select CompanyType from CompanyType"; SqlCommand com = new SqlCommand(strSQL, conn); SqlDataReader dr = com.ExecuteReader(); while ) { this.DropDownList1.Items.Add(dr["CompanyType"].ToString; } } catch (Exception ex) { Response.Write("<scirpt>alert('" + ex.Message.ToString</script>"); } finally { conn.Close(); } } }

public 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"];
this.DropDownList2.DataValueField="编号";
this.DropDownList2.DataTextField="名称";
MyoleAp.Dispose();
}

第一种方法: string ConnString = ConfigurationSettings.AppSettings["ConnectionString"]; //创建一个SqlConnection SqlConnection Conn = new SqlConnection( ConnString );

//DropDownList1的changed改变dorpdownlist2的显示值,

string SQL_Select = "select id, ItemName from DDLItem order by id desc";

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.

//构造一个SqlDataAdapter

SqlDataAdapter myAdapter = new SqlDataAdapter( SQL_Select, Conn);

//开始读取数据

Conn.Open();

DataSet dataSet = new DataSet();

myAdapter.Fill( dataSet,"Table1" );

Conn.Close();

//开始绑定DropDownList

//指定DropDownList使用的数据源

DropDownList1.DataSource = dataSet.Tables["Table1"].DefaultView;

//指定DropDownList使用的表里的那些字段

DropDownList1.DataTextField = "ItemName"; //dropdownlist的Text的字段

DropDownList1.DataValueField = "id";//dropdownlist的Value的字段

DropDownList1.DataBind();

第二种方法:

con.Open();

SqlCommand cmd = new SqlCommand(strSql,con);

SqlDataReader dr = cmd.ExecuteReader();

while )

{ DropDownList1.Items.Add(new ListItem(dr["status"].ToString(), dr["status_Id"].ToString; }

本文由10bet手机官网发布于高并发,转载请注明出处:DropdownList绑定的两种方法,下实现主从DropDownList互动的方法

上一篇:入门代码,为什么会有use 下一篇:0语言规范匿名方法,中的多播委托笔记总结【10bet体育中文官网】
猜你喜欢
热门排行
精彩图文