[英]How to bind a checkedlistbox to a combobox in C#?
我有一個組合框,用戶可以選擇一個項目,並根據checkedlistbox 中的該項目需要填充其他一些項目。
這是用於將源綁定到組合框的代碼,但不適用於這種情況。
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 |
我已經檢查了與我的相關的其他問題,但找不到我的問題的答案。 您的幫助將不勝感激。 謝謝。
更新:這是我發現並為我工作的內容。
// 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.