2013-03-13 71 views
2

我想要的是從下拉列表中選擇的項目中獲取值,並使用它在按鈕單擊事件中查詢(選擇表格)。如何從下拉列表框中獲取值

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     if (DropDownList1.SelectedIndex == 1) 
     { 
      using (SqlConnection con = new SqlConnection(DBcon)) 
      { 

       SqlCommand sqlCommand = new SqlCommand("Select * from tbl_WinApps_FileHeader"); 
       sqlCommand.Connection = con; 

       SqlDataReader read = sqlCommand.ExecuteReader(); 

       GridView1.DataSource = read; 
       GridView1.DataBind(); 


      } 
     } 
    } 

    <asp:DropDownList ID="DropDownList1" runat="server" 
     onselectedindexchanged="DropDownList1_SelectedIndexChanged"> 
     <asp:ListItem>ER00 - File Header</asp:ListItem> 
     <asp:ListItem>ER01 - Expense Report Trans</asp:ListItem> 
     <asp:ListItem>ER02 - Expense Report Item Trans</asp:ListItem> 
     <asp:ListItem>ER03 - Expense Report Item Tax Trans</asp:ListItem> 
     <asp:ListItem>ER04 - Expense Report Item</asp:ListItem> 
    </asp:DropDownList> 

回答

1

您可以使用DropDownListSelectedValue財產。要了解如何將參數添加到where子句中的select查詢,請參閱此post

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    string sel = DropDownList1.SelectedValue.ToString(); 
    // if (DropDownList1.SelectedIndex == 1) 
    // { 
     using (SqlConnection con = new SqlConnection(DBcon)) 
     { 

      SqlCommand sqlCommand = new SqlCommand("Select * from tbl_WinApps_FileHeader"); 
      sqlCommand.Connection = con; 
      SqlDataReader read = sqlCommand.ExecuteReader(); 
      GridView1.DataSource = read; 
      GridView1.DataBind(); 
     } 
    //} 
} 
+0

我在哪裏可以把那一行? – user1954418 2013-03-13 06:42:21

+0

也刪除,如果(SelectedIndex == 1)條件。 該條件沒有任何意義,因爲您希望在SQL查詢中使用SelectedValue。 – 2013-03-13 06:51:37

0

您應該使用SelectedValue屬性。

獲取所選擇的項的值列表中的控制,或選擇在 包含指定值列表控制的項目。

DropDownList1.SelectedValue.ToString(); 

等;

string val = DropDownList1.SelectedValue.ToString(); 
using (SqlConnection con = new SqlConnection(DBcon)) 
{ 
    SqlCommand sqlCommand = new SqlCommand("Select * from tbl_WinApps_FileHeader"); 
    sqlCommand.Connection = con; 

    SqlDataReader read = sqlCommand.ExecuteReader(); 

    GridView1.DataSource = read; 
    GridView1.DataBind(); 
} 

如果你想在你的SqlCommand使用它作爲一個參數,你可以用它喜歡;

SqlCommand sqlCommand = new SqlCommand("Select * from tbl_WinApps_FileHeader WHERE val = @val"); 
sqlCommand.Parameters.AddWithVAlue("@val", val); 
sqlCommand.Connection = con; 
SqlDataReader read = sqlCommand.ExecuteReader(); 
3
DropDownList1.SelectedValue.ToString(); 

或者

DropDownList1.Text; 

或者

DropDownList1.SelectedValue.ToString(); 
相關問題