如何从下拉列表框中获取价值

时间:2013-03-13 06:40:15

标签: c# asp.net winforms

我想要的是从下拉列表中的所选项目中获取值,并使用它在按钮单击事件中查询(选择表格)。

    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>

3 个答案:

答案 0 :(得分:3)

DropDownList1.SelectedValue.ToString();

或者

DropDownList1.Text;

或者

DropDownList1.SelectedValue.ToString();

答案 1 :(得分:1)

您可以使用DropDownList的{​​{3}}属性。要了解如何将参数添加到where子句中的select查询,请参阅此SelectedValue

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();
        }
    //}
}

答案 2 :(得分: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();