ListBox多选方法

时间:2012-09-28 21:47:51

标签: c# ribbon

我有一个列表框和列表视图。当我在列表框上选择多个项目并单击添加时,它会将第一个选定项目添加到列表视图中。我无法克服这个问题。同时,扩展了列表框选择模式。

void reinit()
{
    if (_adrlinks == null)
        return;
    object li = listAdr.SelectedItem;
    listAdr.Items.Clear();
    foreach (LnkAdresse ele in _adrlinks) {
        if (((Filter == eFilter.all) || (Filter == eFilter.basic && ele.RType <= 1) ||
             (Filter == eFilter.synteilnehmer && ele.RType == 8) ||
             (Filter == eFilter.deliveryteam && ele.RType >= 16 && ele.RType <= 31) ||
             (Filter == eFilter.explorationteam && ele.RType >= 32 && ele.RType <= 63)
            ) && (int)ele.mut >= 0)
        {
            listAdr.Items.Add(ele);  //listAdr is my listview
            if (ele == li)
                listAdr.SelectedItem = li;
        }
    }
    //NotifyContent("changeDoc", "", "");
}

2 个答案:

答案 0 :(得分:1)

你的问题非常不清楚,要从列表框中获取多个选定的项目,你使用SelectedItems属性,但是如果你这样做,我必须大胆猜测你想用它做什么。

Pehaps

void reinit()
{
  if (_adrlinks == null) return;
  listAdr.Items.Clear();
  foreach(var li in ListAdr.SelectedItems)
  {
    foreach (LnkAdresse ele in _adrlinks)
    {
      if (((Filter == eFilter.all) || (Filter == eFilter.basic && ele.RType <= 1) || (Filter == eFilter.synteilnehmer && ele.RType == 8)
                || (Filter == eFilter.deliveryteam && ele.RType >= 16 && ele.RType <= 31) || (Filter == eFilter.explorationteam && ele.RType >= 32 && ele.RType <= 63))
                && (int)ele.mut >= 0)
      {
        listAdr.Items.Add(ele);  //listAdr is my listview
        // commented out as it won't ever be true in a multiselect scenario
        // and wouldn't make any sense if it did 
        //if (ele == li) listAdr.SelectedItem = li;
      }
    }
  }
  //NotifyContent("changeDoc", "", "");
}

也许???

答案 1 :(得分:1)

虽然没有直接回答您的问题,但我建议您使代码更具可读性和可维护性。也许你的问题会消失吗?

一个建议:创建一个像这样的过滤方法

private bool TakeLinkAddress(eFilter filter, LnkAdresse linkAddress)
{
    if ((int)linkAddress.mut < 0) {
        return false;
    }
    int rType = linkAddress.RType;
    switch (filter) {
        case eFilter.all:
            return true;
        case eFilter.basic:
            return rType <= 1;
        case eFilter.synteilnehmer:
            return rType == 8;
        case eFilter.deliveryteam:
            return rType >= 16 && rType <= 31;
        case eFilter.explorationteam:
            return rType >= 32 && rType <= 63;
        case else:
            return false;
    }
}

同时为变量提供更好的名称。现在你的循环看起来更好了:

foreach (LnkAdresse linkAddress in _adrlinks) {
    if (TakeLinkAddress(filter, linkAddress)) {
        linkAddressListView.Items.Add(linkAddress);
        if (linkAddress == selectedLinkAddress) {
            linkAddressListView.SelectedItem = selectedLinkAddress;
        }
    }
}