简体   繁体   中英

Top Item On Combo Box

I have windows forms project and List of type DateTime which I want to bind in combobox . I want on top of the combo box to have text 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.

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).

After binding with List<DateTime> you cannot insert item.

Argument exception will be raised 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.

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

in GetUniqueDueDates function you need to add "All"

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"

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 . Something like:

eg: a was suppose to be your dataSource :

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

and property to true before anything else:

comboBox1.Sorted = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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