簡體   English   中英

如何使用Winforms C#獲取用戶在列表框中選擇項目的順序

[英]how do I get the order in which user selected Items in Listbox using Winforms c#

我正在收集用戶從列表框中選擇的所有項目,並在我的應用程序的文本框中輸入值。 但是,我從myListBox.SelectedItems收到的項目始終進行排序,而我需要保留用戶選擇這些項目的順序。

我正在使用Winforms。 我知道WPF中的列表框會返回我想要的內容,但我不是在使用WPF而是簡單的winform和C#。

這是不正確的UI。 如果訂單對您很重要,那么這對用戶也很重要。 除了記住之外,誰沒有辦法告訴他選擇物品的順序。 像電話這樣的簡單中斷就足以丟失。

而是使用兩個列表框。 左邊的選項,右邊的選定項。 提供按鈕以使用戶將它們從一個移到另一個,並在右側的一個中上下移動一個項目。 現在順序是顯而易見的並且可以修改。 您的問題也得到了解決。

我在Google圖片搜索中找到的隨機圖片(忽略樣式選擇):

在此處輸入圖片說明

您可以將事件處理程序添加到SelectedIndexChanged中,以跟蹤選擇了哪些項目以及選擇的順序。 例如:

namespace SandboxTest
{
    public partial class ListBox : Form
    {
        int[] SelectionOrder = new int[50];
        int ClickHistory = 0;

        public ListBox()
        {
            InitializeComponent();
        }

        private void CatchListSelection(object sender, EventArgs e)
        {
            if (ClickHistory == 42)
            {
                ClickHistory = 0;
            }
            SelectionOrder[ClickHistory] = listBox1.SelectedIndex;
            ClickHistory++;
        }
    }
}

然后,變量SelectionOrder包含所選索引的列表。 單擊一些不同的項目后,在調試中看起來像這樣:

調試SelectionOrder數組的顯示

只是不要忘記將“ CatchListSelection”添加到列表框的SelectedIndexChanged事件。

您可以嘗試使用以下代碼來准確輕松地 記錄訂單:

List<int> selectedIndices = new List<int>();
//SelectedIndexChanged event handler for your listBox1
private void listBox1_SelectedIndexChanged(object sender, EventArgs e){
   if (listBox1.SelectedIndex > -1){                
      selectedIndices.AddRange(listBox1.SelectedIndices.OfType<int>()
                                       .Except(selectedIndices));                                                               
      selectedIndices.RemoveRange(0, selectedIndices.Count - listBox1.SelectedItems.Count); 
   }
}
//Now all the SelectedIndices (in order) are saved in selectedIndices;
//Here is the code to get the SelectedItems in order from it easily
var selectedItems = selectedIndices.Select(i => listBox1.Items[i]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM