.DataSource输出重复列表?

时间:2013-02-07 16:48:37

标签: asp.net datasource

当用户从下拉列表中选择一个值并单击该按钮时,该值将添加到第二个列表中(也会显示在屏幕上)。

问题是当用户点击按钮时,所选值将添加到第二个列表,但下拉列表会重复并添加到原始下拉列表中。

因此我们在原始下拉列表中有1,2,3,用户选择“1”并按下按钮。 “1”被添加到第二个列表并显示在屏幕上但是当用户点击下拉列表时它现在包含2,3,1,2,3

我通过断点检查了我的代码,我认为它与.dataSource有关。

protected void UpdatePage()
{
   int Id = System.Convert.ToInt32(Id.Value);

   List<Contractor> allContractors = new List<Contractor>();
   ClarkeDBDataContext db = new ClarkeDBDataContext();

   allSubContractors = (from BoqContractors in db.BOQ_Contractors
                        where BoqContractors.Bill_Of_Quantity_id == tempBoqId
                        select BoqContractors.Contractor).ToList();

   repeaterShowContractorName.DataSource = allContractors;
   repeaterShowContractorName.DataBind();

   IEnumerable<Sub> availableContractors = 
       (from sc in db.Contractors
        select sc).ToList().Except(allContractors);

    //i've tried to set it to null to test it, but to no avail
    DropDownListContractors.DataSource = null;
    DropDownListContractors.DataSource = availableContractors;
    DropDownListContractors.DataBind();
 }

2 个答案:

答案 0 :(得分:2)

由于ViewState和Postback,原始值存在于ddl中。 ddl在Postback上重新填充。这就是原始值存在的原因。

我不确定为什么你需要在这个用例中重新获取db中的数据。如果你确实需要 从数据库刷新列表,只需在设置DropDownListContractors.Clear()之前调用DataSource。这将清除列表。

但是,就像我之前说的那样,我认为你不需要从数据库重新绑定ddl。只需从您的代码中删除这些行(当回发时),它应该按您的意愿工作:

   IEnumerable<Sub> availableContractors = 
       (from sc in db.Contractors
        select sc).ToList().Except(allContractors);

    //i've tried to set it to null to test it, but to no avail
    DropDownListContractors.DataSource = null;
    DropDownListContractors.DataSource = availableContractors;
    DropDownListContractors.DataBind();

答案 1 :(得分:0)

在VB方面,DropDownListContarors.ClearSelection()是不够的,如果你没有选择数据,在我的情况下我没有任何数据,但仍然需要清除列表中的数据。

如果我只使用DropDownListContractors.Items.Clear(),它将清除我的列表中已有的数据,在我的aspx页面中设置。 (我需要保留一行或两行,以及数据绑定数据)。

我找到的唯一解决方法是在页面加载中添加一个条件,无论页面是否已经从我们的数据库中获取了源代码。这些数据不太可能改变。:

If Not Page.IsPostBack Then
  'myComboBox.Items.Clear() 
  'Can't use this, i got one or two items i gotta keep from the aspx page
  'myComboBox.DataSource = Nothing 
  'DOESNT WORK
  myComboBox.DataSource = someSource
  myComboBox.DataBind()
End If

如果我和你的情况一样,我只需要调用items.clear()并在后面的.vb代码中添加我需要的项目。