Top Item On Combo Box - c#

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:
e.g: 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;

Related

How to retrieve selected values for selected items in a ListBox?

I'm populating a ListBox in a WinForms application, this way:
listBoxUsers.DataSource = ctx.Users.ToList();
listBoxUsers.DisplayMember = "Name";
listBoxUsers.ValueMember = "Id";
how to retrieve the selected Ids when I'm setting the SelectionMode to MultiSimple
I want to do a foreach loop on them, like this:
foreach(var itemId in listBoxUsers.SelectedValues)//unfortunately not exist
{
int id = int.Parse(itemId);
// . . .
}
Since you know the type of items, you can use such code:
var selectedValues = listBox1.SelectedItems.Cast<User>().Select(x=>x.Id).ToList();
Side Note: The ListBox control lacks a GetItemValue method. A method which should work like GetItemText, but for getting values. In the linked post I shared an extension method to get the value from an item. Using that extension method you can get selected values independent from type of items:
var selectedValues = listBox1.SelectedItems.Cast<object>()
.Select(x => listBox1.GetItemValue(x)).ToList();
If for some reason you are interested to have a text representation for selected values:
var txt = string.Join(",", selectedValues);
Have you tried with the SelectedItems property?
foreach (var item in listBoxUsers.SelectedItems)
{
}
try this:
foreach (DataRowView item in listBoxUsers.SelectedItems)
{
int id=int.parse(item[0].ToString());
}

BindingSource.Find with no column name

I've got a BindingSource as DataSource for a ComboBox. The BindingSource's source data is a List<String> which obviously doesn't have column names, but only a list of strings. The BindingSource.Find method expects a column name to search on, so I cannot simply use this function. I need to set the ComboBox to a specific selected item and since the source data is a BindingSource, I think it would be best to work with the BindingSource to achieve my goal.
How can I set the correct item in the BindingSource by finding on a specific string value?
Code example:
readonly List<String> _metaList = new List<String>();
...
while (reader.Read())
{
_metaList.Add(reader.GetString(0));
}
comboBoxPartities.DataSource = new BindingSource(_metaList, null);
comboBoxPartities.DisplayMember = "Key";
And later on, I need to achieve something like this:
var bs = (BindingSource) comboBoxPartities.DataSource;
var i = bs.Find("?!!", lastProcessedTable);
((BindingSource) comboBoxPartities.DataSource).Position = i;
You could use List.IndexOf and BindingSource.Position:
List<string> metaList = (List<string>) bs.DataSource;
int position = metaList.IndexOf("foo");
bs.Position = position;
If that string was not found in the list, the first item will be the current item.
Another method that you can use is List.FindIndex which allows to search case-insensitive:
int position = metaList.FindIndex(s => string.Equals(s, "Foo", StringComparison.CurrentCultureIgnoreCase));

Cannot retrieve multiple values from a listbox c#

I am populating a listBox at runtime from a database as follows:
List<FILE_REPORT_TYPES> ReportTypes = GetReportTypesFromDatabase(ReportMappingIds)
BindingList<FILE_REPORT_TYPES> pbReportTypesBindingList = new BindingList<FILE_REPORT_TYPES>(ReportTypes);
listBoxReports.DataSource = ReportTypesBindingList;
listBoxReports.DisplayMember = "REPORT_DESCRIPTION";
listBoxReports.ValueMember = "REPORT_ID";
I then would like select multiple items on the listBox when running the windows form and retrieve each individual Value of my selections. If only one selection is made one could do the following:
listBoxReports.SelectedValue;
I would like to do the following:
var list = listBoxReports.SelectedValues;
However this is not allowed i.e. "SelectedValues" does not exist.
Some people are erroneously suggesting that in this particular case SelectedIndices may be used. It cannot be used, I am trying to retrieve the "VALUE". This cannot be done (in this particular case):
listBox.Items[i].Value;
I think the solution should be along the lines of:
foreach(var line in listBox.Items)
{
var res= ((SOME CASTING)line).Value;
}
To get the selected items you have 2 options
a.) ListBox.SelectedIndices which returns the indices of the selected items which you then need to use to look up in the Items property what the value is or
b.) ListBox.SelectedItems which returns you a collection with the selected items themselves (be aware that it is an objectlist so you need to transform the items into your appropriate datatype).
Edit: With the additional information the following is possible
List<FILE_REPORT_TYPES> mySelectedList = new List<FILE_REPORT_TYPES>();
foreach (Object selectedItem in ListBox.SelectedItems)
{
mySelectedList.Add( ((FILE_REPORT_TYPES)selectedItem) );
}
You can use ListBox.SelectedIndices or ListBox.SelectedItems.
If you want to get all selected-items, you can let the foreach cast:
foreach(FILE_REPORT_TYPES frt in listBox.SelectedItems)
{
// ...
}
or if you want to get the ReportID into a list with the help of LINQ:
List<decimal> reportIds = listBox.SelectedItems.Cast<FILE_REPORT_TYPES>()
.Select(frt => frt.REPORT_ID)
.ToList();
Alternative to the selected value you could do the following
listBoxReports.SelectedItems;
Answer (the casting is the trick):
List<decimal> reportIds = new List<decimal>();
foreach(var line in listBoxReports.SelectedItems)
{
reportIds.Add(((PB_FILE_REPORT_TYPES)line).REPORT_ID);
}
You may try like below
List<FILE_REPORT_TYPES> reportList = new List<FILE_REPORT_TYPES>();
foreach(var item in listBox.SelectedItems)
{
reportList.Add((FILE_REPORT_TYPES)item);
}

C# Combobox move item to bottom of the list

I need to add "Select more..." to the bottom of the combobox items, like it done on SQL 2008 servers selector. Trying like this:
List<string> srvList = new List<string>();
srvList.Add("ff");
srvList.Add("jj");
srvList.Add("pp");
srvList.Add("<Select more...>");
ComboBoxServs.Items.AddRange(srvList.ToArray<String>());
But "Select more..." appears at the top of items.
As MSDN says:
If the Sorted property of the ComboBox is set to true, the items are
inserted into the list alphabetically. Otherwise, the items are
inserted in the order they occur within the array.
Try to set Sorted property to false:
ComboBoxServs.Sorted = false;
List<string> srvList = new List<string>();
srvList.Add("ff");
srvList.Add("jj");
srvList.Add("pp");
srvList.Add("<Select more...>");
ComboBoxServs.Items.AddRange(srvList.ToArray<String>());
You have to use the index of Insert method of Combobox control
myComboBox.Items.Insert(0, "Select more");
hope that help.
you may Refer Here also

C#: Filtering listbox having List<String> as datasource

I have a listbox that has a List assigned as datasource:
List<String> files = new List<String>();
files.Add("test");
files.Add("test2");
ListBox1.DataSource = files;
Now the listbox shows me both entries of the List.
Is there a way to implement an easy filtering mechanism using a textbox?
So if i enter "2" into the textbox just the "test2" entry should be shown anymore.
Any suggestions?
You can filter List like this:
var filteredFiles = files.Where(x=>x.Contains(TextBox1.Text));
and than assign filteredFiles as DataSource
Hope this helps.
Edit:
Try this:
var filteredFiles = files.Where(x=>x.Contains(TextBox1.Text)).ToArray();
or
var filteredFiles = files.Where(x=>x.Contains(TextBox1.Text)).ToList();
Sorry, it has been a while since I did a databinding in asp.net :D
Try this:
ListBox1.DataSource = files.Where(item => item.Contains(textBox.Text));
I'm making an assumption that you want to do this on the client side, not just filter the List object with C#. If that's the case, you can use a jQuery plugin to help. Check out the Filtered List plugin: http://plugins.jquery.com/project/FilteredList
See a demo here: http://emi.github.com/filtered_list/#long-static-list

Categories

Resources