DropDownList使用C#在asp.net中显示重复值

时间:2013-08-14 20:22:56

标签: c# asp.net dropdownlistfor

我只有“是”和“否”,因为我的项目列表在我的下拉列表中,但如果我选择“否”3次,那么它会在我的下拉列表中显示3次,因此它会复制我从下拉菜单中做出的每个选项。在选择之后,它调用存储过程,该过程根据选择将后端更新为是或否。我很困惑,所以请帮忙。谢谢 这是我的DD

的ASPX代码
<asp:DropDownList ID="My_DD" runat="server" 
              AutoPostBack="true" DataTextField="ItemCompleted" AppendDataBoundItems="true" OnSelectedIndexChanged="DD_Changed" 
              DataValueField="ItemCompleted">
              <asp:ListItem Text="Yes" Value="Yes"></asp:ListItem>
                        <asp:ListItem Text="No" Value="No"></asp:ListItem>
          </asp:DropDownList>

这是背后的代码:

protected void DD_Changed(object sender, EventArgs e)
    {
        DropDownList My_DD = (DropDownList)sender;

        this.Bind_DD();

    }   

    protected void Bind_DD()
    {

        string myVar;
        myVar= My_DD.SelectedValue.ToString();
        string ID;
        ID = Request.QueryString["ID"];
        DataTable dt = new DataTable();
        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        SqlDataAdapter sda = new SqlDataAdapter();
        SqlCommand cmd = new SqlCommand("sp_DD");
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@myVAr", SqlDbType.VarChar).Value = myVar;
        cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = ID;
        cmd.Connection = con;
        sda.SelectCommand = cmd;

        sda.Fill(dt);
        My_DD.DataSource = dt;

        My_DD.DataBind();

    }

页面加载代码:

 protected void Page_Load(object sender, EventArgs e)
    {
        string Post_ID = Page.RouteData.Values["Post_ID"] as string;

        if (!IsPostBack)
        {
            BindData();
            BindData_ActionItems();

            //load DV_New
            LoadDetailView_New();       

        }

    }

1 个答案:

答案 0 :(得分:1)

我理解的代码会发生什么: 单击是/否,然后使用来自db的值重新绑定同一下拉列表中的数据。我没有收到错误,但您可以尝试重新添加下拉列表,然后重新添加数据库中的项目

protected void Bind_DD()
{

    string myVar;
    myVar= My_DD.SelectedValue.ToString();
    string ID;
    ID = Request.QueryString["ID"];
    DataTable dt = new DataTable();
    String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);
    SqlDataAdapter sda = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand("sp_DD");
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@My_DD", SqlDbType.VarChar).Value = My_DD;
    cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = ID;
    cmd.Connection = con;
    sda.SelectCommand = cmd;

    sda.Fill(dt);

    My_DD.Items.Clear();

    My_DD.DataSource = dt;
    My_DD.DataBind();

}