简体   繁体   English

组合框上的顶级商品

[英]Top Item On Combo Box

I have windows forms project and List of type DateTime which I want to bind in combobox . 我有windows forms项目和想要绑定在combobox DateTime类型的List。 I want on top of the combo box to have text All . 我想在组合框的顶部输入文字All How to do that ? 怎么做 ?

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

For example 例如

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

You can use the Insert method of the items property to add the extra item. 您可以使用items属性的Insert方法添加额外的项目。

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

This way your datasource does not need to be a list of string. 这样,您的数据源就不必是字符串列表。

Update 更新资料

As mentioned by @Hassan Nisar in the comments, it won't work if you bind the datasource, but you can add items using a loop(refer to @Hassan Nisar's answer for an example). 就像@Hassan Nisar在评论中提到的那样,如果绑定数据源将不起作用,但是可以使用循环添加项(例如,请参阅@Hassan Nisar的答案)。

After binding with List<DateTime> you cannot insert item. List<DateTime>绑定后,您将无法插入项目。

Argument exception will be raised Items collection cannot be modified when the DataSource property is set. Items collection cannot be modified when the DataSource property is set.

Skip binding with data source and add items by iterating through list: 跳过与数据源的绑定,并通过遍历列表添加项:

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

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

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

you need to get the list of dueDtes as string because "All" is string we cant add in Datetime list. 您需要以字符串形式获取dueDtes列表,因为“全部”是我们无法在Datetime列表中添加的字符串。

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

in GetUniqueDueDates function you need to add "All" 在GetUniqueDueDates函数中,您需要添加“全部”

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

//Rest of your code


}

Since your list is of type DateTime , you should first make it to List to make it work when you add "All" 由于您的列表的类型为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;

Try to sort all items after adding another 1 since its all dateTime after All . 尝试添加其他1,因为其所有的日期时间后, 所有以后的所有项目进行排序。 Something like: 就像是:

eg: a was suppose to be your dataSource : 例如: a被假定为您的dataSource

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

and property to true before anything else: 并将属性设置为true之前:

comboBox1.Sorted = true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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