今天咱們來說一講下拉列表及其使用方法。前端
所使用工具:數據庫
Microsoft Visual Studio 2010後端
SQL Server Management Studio工具
ComboBox既是下拉列表this
屬性:spa
Items屬性:爲下拉列表添加相應的項目,與列表框相似.net
DropDownStyle屬性:控制組合框的外觀和功能(此屬性若是選擇DropDownList則只可選擇而不能再框中輸入,若選擇DropDown則便可在框中輸入又能夠進行選擇)code
Sorted屬性:指定是否對組合框的列表部分中的項進行排序server
事件:blog
SelectedIndexChanged事件:選擇下拉框中的選項時發生
首先,咱們是綁定數據庫。咱們就要創建一個數據庫。我這裏創建了一個叫T2的數據庫,只有兩行數據。
T2
創建完成了之後,就開始在VS中實現咱們的目標了!
創建三層,在我第一篇文章中寫入了http://www.javashuo.com/article/p-chbywqsv-bu.html
而後,呵呵,上代碼~
Model層(Symboluser類): using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Model { public class Symboluser { public string id { set; get; } public string symbol { set; get; } } }
DAL層(dal類): using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace DAL { public class dal { public List<Model.Symboluser> ToSelectSymbol(string where) { DataSet ds = SQLDispose. ToGetData (" select * from T2 " + where); if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0) { List<Model.Symboluser> MyList = new List<Model.Symboluser>(); Model.Symboluser Myuserlist = null; foreach (DataRow item in ds.Tables[0].Rows) { Myuserlist = new Model.Symboluser(); Myuserlist.id = item["id"].ToString(); Myuserlist.symbol = item["symbol"].ToString(); MyList.Add(Myuserlist); } return MyList; } else { return null; } } Public class SQLDispose { static string ConnStr = "Data Source=.;Initial Catalog=調用的數據庫名;Persist Security Info=True;User ID=數據庫用戶名;Password=數據庫密碼"; public static DataSet ToGetData (string Sql) { using (SqlConnection Conn = new SqlConnection(ConnStr)) { using (SqlDataAdapter da = new SqlDataAdapter(Sql, Conn)) { DataSet ds = new DataSet(); Conn.Open(); da.Fill(ds); da.Dispose(); return ds; } } } } } }
BLL層(bll類): using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BLL { public class bll { DAL.dal Mydal = new DAL.dal(); public List<Model.Symboluser> ToSelectSymbol() { return Mydal.ToSelectSymbol(" "); } } }
UI層(前端): <asp:DropDownList ID="DropDownList1" runat="server" Width="93%" Height="86%"> </asp:DropDownList> (由於前端只須要加這個控件就行) UI層(後端): using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace UI { public partial class SheZhi : System.Web.UI.Page { BLL.bll Mybll = new BLL.bll(); protected void Page_Load(object sender, EventArgs e) { Boon(); } public void Boon() { if (!IsPostBack) { List<Model.Symboluser> Mysymbol = new List<Model.Symboluser>(); Mysymbol = Mybll.ToSelectSymbol(); DropDownList1.DataTextField = "symbol"; DropDownList1.DataValueField = "symbol"; DropDownList1.DataSource = Mysymbol; DropDownList1.DataBind(); this.DropDownList1.Items.Insert(0, new ListItem("==請?選?擇?==")); } } } }
最後點擊運行,就成功啦~
效果以下:
是否是很簡單~