1.與資料庫綁定
SqlConnection conn= new SqlConnection(ConfigurationSettings.AppSettings["job"]);//資料庫連接資訊
SqlCommand myCommand = new SqlCommand( "select * from info", conn ); //SQL命令
myCommand.Connection.Open(); //開啟資料庫
SqlDataReader myReader = myCommand.ExecuteReader(); //擷取資料
while ( myReader.Read() )
{
DropDownList.Items.Add( new ListItem( myReader["depsimplename"].ToString(),myReader["depcode"].ToString()));//增加dropwoenlist項
}
myCommand.Connection.Close(); //關閉資料庫
若要指定綁定後的資料選定項
可使用DropDownList.Items.FindByText("name").Selected=true或者 DropDownList.Items.FindByValue("code").Selected=true
另外也可從資料庫中獲得選定項(比如修改資訊的時候)
可使用先用資料庫填充一個DateSet--ds,然後使用DropDownList.Items.FindByValue/*或者FindByText*/(ds.Tables[0].Rows[0].ItemArray[0].ToString()).Selected=true;
2.查詢用法
對於單個下拉式功能表查詢我一般直接使用SelectedIndexChanged事件,使用這個事件千萬別忘記把下拉式功能表的AutoPostBack屬性設為true!
private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
strSQL="select * from info where name="+DropDownList.SelectedItem.Text;//SQL命令與選項綁定
...//再執行這個命令即可
}
而對於多個下拉式功能表聯集查詢我則使用增加一個按鈕,這樣更方便
private void Button1_Click(object sender, System.EventArgs e)
{
strSQL="select * from info where name1 like '%"+DropDownList1.SelectedItem.Text+"' and name2 like '%"+DropDownList2.SelectedItem.Text+"' ;//請注意我用的是like
Admin.cc Detail=new Admin.cc();//自己定義的一個類,Detail的傳回值是一個dataset
infoDataGrid.DataSource = Detail.Display(strSQL.Replace("全部",""));//聯集查詢中使用者往往不會把使用所有的下拉式功能表,所以我加了一個'全部'的選項,不知道你們看到這裡 明不明白我為什麼要使用like了,呵呵
infoDataGrid.DataBind();
------------------------------------------------------------------------------------------------------------------------------------------------
添加選項並設為喜好設定的另一種寫法:
ListItem ListItem1=new ListItem("text","value");
DropDownList1.Items.Add(ListItem1);
DropDownList1.SelectedValue="value";
}