trying to compare the Selected Value of an array of ComboBoxes - c#

Trying to make an application in C# using Windows Forms in Visual Studio Version 15. Id like to be able to check to make sure each selected item is different in each comboBox. I've discovered that you can create an array of controls but the problem I'm having is in accessing the values in that array to check each one programmaticly
how could I use this array to check to see if all values are unique and return a simple bool?
Control[] statboxes = { comboBoxA, comboBoxB, comboBoxC, comboBoxD, comboBoxE, comboBoxF };

You can use linq like this:
var result = statboxes.Distinct().Count() == statboxes.Count();
Edit:
To check the unique selected item try this:
var result = statboxes.Select(s => ((ComboBox)s).SelectedItem).Distinct().Count() == statboxes.Select(s => ((ComboBox)s).SelectedItem).Count();

With Combobox.selectedindex you can select an item based on their index nr. And with Combobox.selectedvalue, you can select an item based on their name.
As for picking the unique values, you can use Combobox.Distinct().Count, which is explained in t2t's answer.

You can utilize HashSet<T>.Add(value) method with Enumerable.All extension method
// For example combobox values is of type int
var values = new HashSet<int>();
var isUnique = statboxes.All(combobox => values.Add((int)combobox.SelectedValue));
HashSet<T>.Add method will return true if given value was successfully added to the set and false if given value already exists.

Use ComboBox array instead of Control so you no need to cast it while doing your operation:
ComboBox[] statboxes = { comboBoxA, comboBoxB, comboBoxC, comboBoxD,
comboBoxE, comboBoxF };
Then check if all of the comboboxes has unique selected value:
bool IsAllComboBoxesHasDistinctSelectedValue = statboxes.Select<ComboBox,string>((cb) =>cb.SelectedValue.ToString()).Distinct().Count() == statboxes.Count();

Related

foreach Certain item is in a ListBox - Winform, C#

I would like to know how I could find the amount of times a certain item appears in a listbox
foreach (string Item in listBox1.Items)
{
Console.WriteLine("1 Item");
}
Console.ReadLine();
Unfortunately, that cycles through the entire listBox. I only want a certain Item.
Assuming that listBox1.Items : List<string> or string[] ...
Option 1: listBox1.Items.Count(item => item == "YourCertainItem");
You could use Linq
Option 2: listBox1.Items.Where(item => item == "YourCertainItem").Count();
It would depend on the type of data you have bound to the ListBox and the types unique identifer (or the property you want to use for comparison).
For example, if you have bound a list of String to the Listbox, you could use
var result = listBox.Items.OfType<String>().Count(x=>x == valueToSearch);
Instead, if you have bound a Collection of Person Types to the ListBox, where Person.Id is the property you want to use for comparison, you could use
var result = listBox1.Items.OfType<Person>().Count(x=>x.Id == personToSearch.Id);
You need to begin by defining what would be the property you would compare the items in the ListBox by, after which you could use Linq as shown in the examples above.

How to get multiple selected values from listbox C# Windows Application

I am using a Listbox on my windows application. The listbox has a multi-selection option, which users select all the roles the new user will have.
My Listbox is bound to a dataset. The table is Roles, with an ID column and Description column.
When I bound the listbox, I chose the data source being the dataset, the display member to be the description, the value member being the ID and the selected value being the dataset - roles.frolesid
Now when i loop through the listbox's selecteditems, i get only the first item's values etc...
I am trying to assign an int to the current selectedvalue, to get the ID to give to the user.
int num = 0;
foreach (var item2 in lstRoles.SelectedItems)
{
num = Convert.ToInt32(lstRoles.SelectedValue);
}
So if I select 3 roles, for instance Administrator, Capturer and Assessor, I only see the Administrator value.
How do I loop and access the next item? I'm not even using
item2
in my code. Could this be utilised?
For instance:
First iteration:
And it just stays on that selected item, never moving to the next item.
To get list of selected values when the data source is a DataTable, you can use this code:
var selectedValues = listBox1.SelectedItems.Cast<DataRowView>()
.Select(dr => (int)(dr[listBox1.ValueMember]))
.ToList();
But in general Item of a ListBox control may be DataRowView, Complex Objects, Anonymous types, primary types and other types. Underlying value of an item should be calculated base on ValueMember.
If you are looking for a good solution which works with different settings and different data sources, you may find this post helpful. It contains an extension method which returns value of an item. It works like GetItemText method of ListBox.
solved it
int num = 0;
int count = fRoleIDs.Count;
while (num != count)
{
var item = lstRoles.Items[num] as System.Data.DataRowView;
int id = Convert.ToInt32(item.Row.ItemArray[0]);
num += 1;
}
This goes into the listbox's items and according to the index, gets the item as a Row. This then gets me the itemarray, which is ID and Description {0,1}

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);
}

combobox item selected To be fixed

I had a databound combobox in my windows form I populate it by a function deptload() IN FORM LOAD
public void DeptcomboLoad()
{
DataTable dt = depttrans.getDeptName();
Cmb_Department.DataSource = dt;
Cmb_Department.DisplayMember = "DepartmentName"; //CHAR
Cmb_Department.ValueMember = "DepartmentPK"; //INT
}
Now when an employee of a department (say accounts DepartmentName="Accounts " , DepartmentPK=23 ) login I want the ComboBox text to be selected as "acounts "
and when I go to get the selected value of the ComboBox I should get 23
I tried
Cmb_Department.selectedtext="Accounts"
Cmb_Department.Text="Accounts"
but its not giving the selected value
Can anyone give a suggestion
Instead of trying to put a value INTO the combobox, try to GET the SelectedItem like this:
string txt= Cmb_Department.SelectedItem.Text
or just:
string txt= Cmb_Department.SelectedText
To change selected value of the combobox you can use
SelectedItem property or SelectedIndex.
Index must be exact number in your data sourse, and Item must be exact object from datasource
You can get it to select the right item by issuing something like this:
Cmb_Department.SelectedValue = 23;
Where 23 comes from some other variable, maybe on another object, maybe from a local variable, whatever works in your case.
Now, to get the selected value you can use this statement:
var val = Cmb_Department.SelectedValue;
To get the selected text (which would be the text associated with the value):
var text = ((DataRow)Cmb_Department.SelectedItem)["DepartmentName"];
The reason I'm prescribing the aforementioned is because the SelectedText property is volatile, and the Text property doesn't always work based on how the DropDownStyle is set.
However, some would probably argue to get the same as the aforementioned you could issue this statement:
var text = Cmb_Department.Text;

How to remove an Item from a combobox when a datasource is assigned to an enum?

How to remove an Item from a combobox when a datasource is assigned to an enum?
When trying to remove by Items.Remove, got error:
Items collection cannot be modified when the DataSource property is set.
Any suggestion?
Note: I would keep using the enum because I deal it in many places in the code.
The code:
public enum DefaultValueType
{
None = 0,
Static = 1,
Query = 2
}
cBoxDefaultType.DataSource = Enum.GetValues(typeof(DefaultValueType));
In one case, I want to remove the Query item from the options of the combobox.
cBoxDefaultType.Items.RemoveAt(2); // Throw exception
I found the solution by filtering the array of Enumeration:
Enum.GetValues(typeof(DefaultValueType))
.Cast<DefaultValueType>()
.Where(p => p != DefaultValueType.Query)
.ToArray<DefaultValueType>()
You need to remove item from DataSource and rebind or use just .Items withoutDataSource
In your case you need to convert Enum to array and then work with it.
Also for .NET 2.0 (Remove 'Invalid' item from enum 'SomeEnum'):
comboBox1.DataSource = Array.FindAll((SomeEnum[])Enum.GetValues(typeof(SomeEnum)),
(SomeEnum SM) => { return SM != SomeEnum.Invalid; });

Categories

Resources