根据从不同下拉列表中选择的值填充下拉列表

时间:2013-10-14 11:37:28

标签: c# asp.net

我想根据从其他dropdownlist中选择的房型填写我的dropdownlist房间号码。但是,在从dropdown中选择房型时,其他dropdown中的值每次都会重复。这是sql表和程序。

Room num, Room type,  Cost,    Status
A1        AC          223     Av
B2        Non Ac      180     Av

public partial class customer_reservation : System.Web.UI.Page
{
    string connectionString = WebConfigurationManager.ConnectionStrings["newdb"].ConnectionString;
   protected void Page_Load(object sender, EventArgs e)
   { 
   }
   protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
   {

    string rval = DropDownList1.SelectedValue.ToString();

    SqlConnection con = new SqlConnection(connectionString);
    con.Open();
    string qry = "select Roomnum from room where rtype=@rval and rstatus like 'AV'";
    SqlCommand cmd = new SqlCommand(qry,con);
    cmd.Parameters.AddWithValue("@rval",rval);
    SqlDataReader rd1 = cmd.ExecuteReader();

        if (rd1.HasRows)
        {
            while (rd1.Read())
            {
                DropDownList2.Items.Add(rd1[0].ToString());
            }
        }
        con.Close();
   }
}

3 个答案:

答案 0 :(得分:0)

解决此问题的最简单方法是清除第二个下拉列表中的项目集合,然后开始填充它。

简单DropDownList2.Items.Clear()应该可以解决问题。

答案 1 :(得分:0)

在第一个下拉列表中选择的索引已更改

将第二个列表绑定到其数据源。

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    if(true) // your check condition
    {
     //clear previous values using .Clear()
     dropdownlist2.Items.Clear()
     //bind the second dropdownlist to new options
     //or add options
    }
}

答案 2 :(得分:0)

使用此

DropDownList2.Items.Clear();

向你的职能DropDownList1_SelectedIndexChanged

致敬
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList2.Items.Clear();
    string rval = DropDownList1.SelectedValue.ToString();

    SqlConnection con = new SqlConnection(connectionString);
    con.Open();
    string qry = "select Roomnum from room where rtype=@rval and rstatus like 'AV'";
    SqlCommand cmd = new SqlCommand(qry,con);
    cmd.Parameters.AddWithValue("@rval",rval);
    SqlDataReader rd1 = cmd.ExecuteReader();
    if (rd1.HasRows)
    {
        while (rd1.Read())
        {
                DropDownList2.Items.Add(rd1[0].ToString());
        }
    }
    con.Close();
}