列表框删除

时间:2016-01-22 20:41:30

标签: c# winforms

我有一个列表框,有2个按钮,new和delete。 new将一个项添加到列表框中,删除按钮应该从列表框中删除该项。列表框项目绑定到一个类,该类存储用户从下面的文本框输入的数据。

 private void AddListBox()
    {           
        lstCondition.BeginUpdate();
        Condition cond = new Condition("");

        cond.Name = string.Format("Condition {0}", _selection.NetConditions.Count + 1);
        _selection.NetConditions.Add(cond);

        lstCondition.EndUpdate();

        lstCondition.SelectedItem = cond;                     

        cboNetCondition.Properties.Items.Clear();
        cboNetCondition.Properties.Items.AddRange(NetCondition);
        cboControlType.Properties.Items.Clear();
        cboControlType.Properties.Items.AddRange(ControlType);
        cboFlowRate.Properties.Items.Clear();
        cboFlowRate.Properties.Items.AddRange(FlowRate);
    }

 private void btnNew_Click(object sender, EventArgs e)
        {
            AddListBox();

        }

cbo项是组合框,其数据在条件类中与列表框的每个实例相关联。

 public frmNetConditions(Condition condo, Selection selection)
    {
        InitializeComponent();
        _selection = selection;
        lstCondition.DataSource = _selection.NetConditions;
        condition = _selection.NetConditions.Count;

    }

 private void btnDelete_Click(object sender, EventArgs e)
    {

        selectedCondition = (Condition)lstCondition.SelectedItem;

        cboControlType.SelectedIndex = -1;
        cboNetCondition.SelectedIndex = -1;
        cboFlowRate.SelectedIndex = -1;
        txtFlowRate.Text = string.Empty;
        txtStatPressure.Text = string.Empty;
        txtDampOpening.Text = string.Empty;
        txtDensity.Text = string.Empty;
        cboDensity.SelectedIndex = -1;

        lstCondition.Items.Remove(lstCondition.SelectedItem);
        lstCondition.Refresh();


    }

按下此删除按钮后,列表框仍然包含我要删除的项目,我不确定为什么会这样?

使用数据源进行更新

 public List<Condition> NetConditions { get { return _netconditions; } }

1 个答案:

答案 0 :(得分:0)

如上所述,您应该绑定到BindingList<Condition>而不是List<Condition>。这允许您更改数据源和控件(ListBox)以通知您的更改。代码应如下所示:

lstCondition.ValueMember = "ConditionId";
lstCondition.DisplayMember = "Name";
lstCondition.DataSource = NetConditions;

定义绑定后,ListBox项目的正确操作方式是从datasource删除,而不是从ListBox本身删除:

// SelectedItem should be checked for null (no selection is an option)
NetCondition.Remove((Condition)lstCondition.SelectedItem);

但是,如果您计划更改元素的属性(因此,而不是列表本身),则仅当您的元素(Condition)实现INotifyPropertyChanged接口时才会通知控件。