簡體   English   中英

如何在 C# 中將選中的列表框綁定到組合框?

[英]How to bind a checkedlistbox to a combobox in C#?

我有一個組合框,用戶可以選擇一個項目,並根據checkedlistbox 中的該項目需要填充其他一些項目。

  1. 當列中的所有值都不同時,我可以將組合框綁定到數據庫中的列。 但是,在這種情況下,該列中有重復的項目,我不想有多個相同類型的項目。 我只想在組合框中有一個“爬行者”和一個“全地形”。

這是用於將源綁定到組合框的代碼,但不適用於這種情況。

comboBox1.ValueMember = "crane index";
comboBox1.DisplayMember = "crane type";
comboBox1.DataSource = test.Tables["cranemaintable"];

這是數據庫中的表

| Crane Index | Crane Model Number |  Crane Type |
|:-----------:|:------------------:|:-----------:|
| 221         | LR 1400-1          | Crawler     |
| 258         | CC 2800            | Crawler     |
| 262         | CC 2400-1          | All Terrain |
| 265         | CC 6800            | Crawler     |
| 277         | LR 11350           | All Terrain |
  1. 數據庫:MS Access
  2. 數據集:測試
  3. 表名:起重機維護台

我已經檢查了與我的相關的其他問題,但找不到我的問題的答案。 您的幫助將不勝感激。 謝謝。

更新:這是我發現並為我工作的內容。

// create a list that holds all the crane types but it should not have duplicated items
        List<string> crane_type = new List<string>();
        for (int i = 0; i< test.Tables["cranemaintable"].Rows.Count; i++)
        {
            if (!crane_type.Contains(test.Tables["cranemaintable"].Rows[i]["crane type"]))
            {
                crane_type.Add(Convert.ToString(test.Tables["cranemaintable"].Rows[i]["crane type"]));
            }                
        }        
        //bind the crane_type list to the combobox1
        comboBox1.DataSource = crane_type;

好的,首先我的答案很丑陋,但它有效,並且是我唯一知道的,所以我們從您將數據庫表導入列表開始,這是您可以使用的類

public class myclass
   {
      public string CraneIndex { get; set; }
      public string CraneModelNumber { get; set; }
      public string CraneType { get; set; }
   }

然后列出 3 個列表

  List<myclass> myclasses = new List<myclass>();
  List<myclass> myclasses1 = new List<myclass>();
  List<myclass> myclasses2 = new List<myclass>();

在這里,您將表導入myclasses列表,然后我們過濾來自數據庫的主列表,使其僅具有唯一類型

      myclasses1 = myclasses.GroupBy(myclass => myclass.CraneType).Select(x => x.First()).ToList();
      comboBox1.DataSource = myclasses1;
      comboBox1.DisplayMember = "CraneType";

轉到combobox並訂閱selectedindexchanged屬性並將其添加到其函數中

 myclasses2.Clear();
    foreach (var item in myclasses)
    {
       if (comboBox1.Text==item.CraneType)
       {
         myclasses2.Add(item);
       }
    }
    checkedListBox1.Items.Clear();
    foreach (var item in myclasses2)
    {
        checkedListBox1.Items.Add(item.CraneModelNumber);
    }
    this.checkedListBox1.DisplayMember = "cranemodels";
    checkedListBox1.Refresh();

如果您需要更多幫助或解釋,請告訴我。

暫無
暫無

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

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