簡體   English   中英

組合框上的頂級商品

[英]Top Item On Combo Box

我有windows forms項目和想要綁定在combobox DateTime類型的List。 我想在組合框的頂部輸入文字All 怎么做 ?

List<DateTime> dueDates = manager.GetUniqueDueDates();
cbDates.DataSource = dueDates;

例如

All
1/1/2001
1/1/2002
1/1/2003

您可以使用items屬性的Insert方法添加額外的項目。

cbDates.Items.Insert(0, "All");

這樣,您的數據源就不必是字符串列表。

更新資料

就像@Hassan Nisar在評論中提到的那樣,如果綁定數據源將不起作用,但是可以使用循環添加項(例如,請參閱@Hassan Nisar的答案)。

List<DateTime>綁定后,您將無法插入項目。

Items collection cannot be modified when the DataSource property is set.

跳過與數據源的綁定,並通過遍歷列表添加項:

List<DateTime> dueDates = manager.GetUniqueDueDates();
//cbDates.DataSource = dueDates;

foreach (var date in dueDates)
     cbDates.Items.Add(date)

cbDates.Items.Insert(0, "All");

您需要以字符串形式獲取dueDtes列表,因為“全部”是我們無法在Datetime列表中添加的字符串。

List<string> dueDates = manager.GetUniqueDueDates();

在GetUniqueDueDates函數中,您需要添加“全部”

public List<string> GetUniqueDueDates()
{
List<string> uniqueDate=new List<string>();
uniqueDate.add("All");

//Rest of your code


}

由於您的列表的類型為DateTime,因此,當您添加“全部”時,應首先將其添加到列表中以使其起作用

List<string> dueDates = new List<string>();
dueDates.Add("All");
dueDates.Add(new DateTime(2001,03,01).ToString());
dueDates.Add(new DateTime(2002, 04, 01).ToString());
dueDates.Add(new DateTime(2003, 05, 01).ToString());
cbDates.DataSource = dueDates;

嘗試添加其他1,因為其所有的日期時間后, 所有以后的所有項目進行排序。 就像是:

例如: a被假定為您的dataSource

comboBox1.Items.AddRange(a.OrderBy(c => c).ToArray());

並將屬性設置為true之前:

comboBox1.Sorted = true;

暫無
暫無

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

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