简体   繁体   中英

ListBox with possibility to group by category and A-Z

I have two list of Parameters, where you can move them between the two (include or not) and I want to customize the order of the Parameters to simplify the selection.

I am currently using a ListBox with multiple selection, but I want it to have a group by feature to group by category , AZ or custom sort like a propertyGrid .

Is there a component that can do all of those? What settings do I need to set on that component?

I would use a ListView which supports groups like it does in the Windows Explorer views.

check this one: How to: Group Items in a Windows Forms ListView Control

so in short, you first create a group:

// Adds a new group that has a left-aligned header
listView1.Groups.Add(new ListViewGroup("List item text",
    HorizontalAlignment.Left));

then you add items to a group for example here the item 0 is added to the group:

// Adds the first item to the first group
listView1.Items[0].Group = listView1.Groups[0];

If you decide to use a ListView - here's a solution to use column-based sorting. I use it in a component, inheriting ListView.

private ListViewItemComparer LviComparer = new ListViewItemComparer(); // Comparer Class

// Override OnColumn Click
protected override void OnColumnClick(ColumnClickEventArgs e)
{
  if (e.Column == LviComparer.SortColumn)
  {
    if (LviComparer.Order == SortOrder.Ascending)
    {
      LviComparer.Order = SortOrder.Descending;
    }
    else
    {
      LviComparer.Order = SortOrder.Ascending;
    }
  }
  else
  {
    LviComparer.SortColumn = e.Column;
    LviComparer.Order = SortOrder.Ascending;
  }
  this.Sort();
  base.OnColumnClick(e);
}

// Compare Class

 public class ListViewItemComparer : IComparer  {
  public int SortColumn  {  get ; private set ; }
  public SortOrder Order {  get ; private set ; }
  private CaseInsensitiveComparer objectCompare = new CaseInsensitiveComparer();
  public int Compare(object x, object y)
  {
    int compResult = 0;
    ListViewItem lviX, lviY;
    lviX = (ListViewItem)x;
    lviY = (ListViewItem)y;
    compResult = CompareString(lviX, lviY);
            if (Order == SortOrder.Ascending)
    {
      return compResult;
    }
            else if (Order == SortOrder.Descending)
    {
      return (-compResult);
    }
    else
    {
      return 0;
    }
  }
private int CompareString(ListViewItem lviX, ListViewItem lviY)
{
  try
  {
            int compareResult = objectCompare.Compare(lviX.SubItems[SortColumn].Text, lviY.SubItems[SortColumn].Text);
    return compareResult;
  }
  catch (IndexOutOfRangeException ex)
  {
    Console.WriteLine(ex.Message);
    return 0;
  }
} }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM