Getting all values from Checkboxlist - c#

I have a array of 13 strings in which I pull the string values from checkboxlist. I can pull the values that are selected with the code below. However I want to also pull the unchecked values as null. So if I select 12 values then 1 would be null in the array.
I'm not sure if the array is dynamically adding the selected values or if the code fills the uncheck values with null. Please help.Thank you.
string[] selectedAreaValues = new string[13];
IEnumerable<string> allChecked = (from item in ceCheckBoxList.Items.Cast<ListItem>()
where item.Selected
select item.Value);
selectedAreaValues = allChecked.ToArray();

If you want to always return the same number of items as in the original Items collection, but project selected items to their value and unselected items to null, then something like this should work:
IEnumerable<string> allChecked = (from item in ceCheckBoxList.Items.Cast<ListItem>()
select item.Selected ? item.Value : (string)null);

We may also use the alternative syntaxe + A concat between the two sequences
IEnumerable selectedItems = ceCheckBoxList.Items.Cast().Where(item => item.Selected).Select(item => new String(item.Value.toCharArray()));
Using a negation with the item.Selected boolean expression in the Where clause and using a Concat between the two sequences.

Related

trying to compare the Selected Value of an array of ComboBoxes

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

c# - get multiple listbox values and turn into comma separated string winforms

I want to get all the selected list items in my listbox and put their values into a comma separated string. I populate the listbox using a List containing my custom object TestSubject which contains a TestSubjectID and TestSubjectName:
var objTestSubjectList = new List<TestSubject>();
//code that adds items to List
I then map the Listbox datasource to this list and set the DisplayMember, ValueMember correspondingly:
lbTestSubjects.DataSource = objTestSubjectList;
lbTestSubjects.DisplayMember = "TestSubjectName";
lbTestSubjects.ValueMember = "TestSubjectID";
When the multiple items in the listbox have been selected, I want to grab the values for each item (the TestSubjectID) and place them in a comma separated string. For example, if 3 items are selected with TestSubjectIDs of 10 20 and 30 I want to loop through and grab the values and put them in a string like so: "10,20,30". I am using windows forms. How would I accomplish this?
You need to loop over the SelectedIndices collection, retrieve the TestSubject object stored in the Item corresponding to the index selected and then add its TestSubjectID value to a list of integers. Finally string.Join will create the string for you.
List<int> ids = new List<int>();
foreach(int x in lbTestSubjects.SelectedIndices)
{
TestSubject t = lbTestSubjects.Items[x] as TestSubject ;
ids.Add(t.TestSubjectID);
}
string result = string.Join(",", ids);
Console.WriteLine(result);
This code could also be reduced a lot using LINQ
var ri = lbTestSubjects.SelectedIndices
.OfType<int>()
.Select(i => ((TestSubject)lbTestSubjects.Items[i]).TestSubjectID);
string result = string.Join(",", ri);

How to check if a value already exist in list box before adding to it in asp.net

how can I check if the value is already present in a list-box, so that I can avoid duplicates?
I've added some values to the server-side list-box already, and when I add to list I get more duplicates.
How do I avoid duplicates?
lst_Viewers.Items.Add(reader["Name"].ToString());
ListItem item = new ListItem(reader["Name"].ToString());
if ( ! lst_Viewers.Items.Contains(item) ){
lst_Viewers.Items.Add(item);
}
or
var name = reader["Name"].ToString();
ListItem item = lst_Viewers.Items.FindByText(name);
if ( item == null ){
lst_Viewers.Items.Add(new ListItem(name));
}
if(!lst_Viewers.Items.Any(item => item.Value.ToString().Equals(reader["Name"].ToString())
lst_Viewers.Items.Add(reader["Name"].ToString());
Another approach can be to insert all the values into a List<string> then add the items only after the loop, using .Distinct() to get only unique values:
List<string> names = new List<string>();
while (reader.Read())
names.Add(reader["Name"].ToString())
names.Distinct().ToList().ForEach(name => lst_Viewers.Items.Add(name));
This way you don't have to search the whole DropDown in every iteration - more elegant (in my opinion) and more efficient.

Linq to sql between List and Comma separated string

I Have one list and one comma separated column value.
lst.Add("Beauty");
lst.Add("Services");
lst.Add("Others");
And Column value is like
Beauty,Services
Service,Others
Beauty,Others
Other,Services
Other
Beauty, Food
Food
Now I Want all those rows which contains any list item.
Output result is
Beauty,Services
Service,Others
Beauty,Others
Other,Services
Other
Beauty, Food
First Edit
These comma separated values are one of my table's one column value.
I need to check against that column.
Assuming you can figure out how to get the RowCollection
RowCollection.Where(row => row.Split(",").ToList().Where(x => list.Contains(x)).Any()).ToList();
will evaluate to true if the row contains a value from the list.
try
List<string> lst = ....; // your list of strings
string[] somecolumnvalues = new string[] { "", "",... }; // your columvalues
var Result = from l in lst from c in somecolumnsvalues where c.Contains (l) select c;

How to check if an item exists in more than one listbox? ASP.NET/C#

I have three sets of listboxes, I move items from lb1 to lb2, from lb3 to lb4 and from lb5 to lb6. The listboxes on the left contains the same items and I don't want the user to be able to submit the page if one or more items from the left listboxes is added to more than one listbox to the right. For example, item A in lb1, lb3 and lb5 can only be saved in either lb2, lb4 or lb6, not in two or three of them.
I want to perform this check before submitting the page (and later on I will add validation with javascript) and I wonder what is the most efficient way to do this.
Add all items to a list and check if there are any duplicates?
Thanks in advance.
Edit:
something like this:
List<string> groupList = new List<string>();
foreach (ListItem item in lbFullAccess.Items)
{
groupList.Add(item.Value.ToString());
}
foreach (ListItem item in lbContributor.Items)
{
groupList.Add(item.Value.ToString());
}
foreach (ListItem item in lblReadOnly.Items)
{
groupList.Add(item.Value.ToString());
}
Well, there's a hundred different ways you could do it. Absolutely nothing wrong with your suggestion of iteration.
You could have a little fun with LINQ:
public bool AreAllValuesUnique()
{
// Build up a linq expression of all of the ListItems
// by concatenating each sequence
var allItems = lbFullAccess.Items.Cast<ListItem>()
.Concat(lbContributor.Items.Cast<ListItem>())
.Concat(lbReadOnly.Items.Cast<ListItem>());
// Group the previous linq expression by value (so they will be in groups of "A", "B", etc)
var groupedByValue = allItems.GroupBy(i => i.Value);
// Finally, return that all groups must have a count of only one element
// So each value can only appear once
return groupedByValue.All(g => g.Count() == 1);
}
Not really sure about the performance of calling Cast (converting each element of the ListItemCollection to a ListItem, resulting in an IEnumerable) on each collection, but it is probably negligible.

Categories

Resources