2013-03-13 148 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();