下拉式功能表dropdownlist一些用法

來源:互聯網
上載者:User

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";

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.