How to loop through an array of checkbox - c#

I am working on an windows application and I am wondering what is the way to loop through an array of checkBox to see if they are checked or not and have a message box to show what is checked.
Here is the code i am using.
CheckBox[] myCheckBoxArray = new CheckBox[6];
myCheckBoxArray[0] = checkBoxALL;
myCheckBoxArray[1] = checkBoxA;
myCheckBoxArray[2] = checkBoxB;
myCheckBoxArray[3] = checkBoxC;
myCheckBoxArray[4] = checkBoxD;
myCheckBoxArray[5] = checkBoxE;
foreach(var items in myCheckBoxArray)
{
if(myCheckBoxArray.Checked)
{
MessageBox.Show(items);
}
}

You can use linq:
foreach(var checkedItem in myCheckBoxArray.Where(item => item.Checked))
{
MessageBox.Show(checkedItem);
}

You are looping through myCheckBoxArray, where items represent each item in the array, so you have to check whether the item is checked or not not the myCheckBoxArray.Checked. so your code will be like the following:
foreach(var items in myCheckBoxArray)
{
if(items.Checked)
{
//Do your stuff here
}
}

Dont loop not checked items .
var checkeeditems=myCheckBoxArray.where(p=>p.Cheked).toList();
foreach(var Name in checkeeditems)
{
MessageBox.Show(Name );
}

In the example code, you are looping through mycheckboxarray, but you are checking Checked property of myCheckBoxArray rather than item. You can alter the code as below and it will give you desired results.
foreach (var checkbox in myCheckBoxArray)
{
if (checkbox.Checked)
{
MessageBox.Show("this one is checked");
}
}

Related

c# How to prevent duplicate listview by column text

I need to prevent Duplicate entries from ListView controller by column text. if duplicate found I need to get the ListView Item for further process. I saw every one says
ListViewItem item = ListView3.FindItemWithText("test");
if (!listView1.Items.ContainsKey(txt))
{
// doesn't exist, add it
}
but how can I point which Column text?? I did prevent duplicates by adding ids into a array and after check array value exists. but in that case I can find which entry duplicated.
this is my code.
rd = cmd.ExecuteReader();
// Validation not working - duplicating ListviewItems
while (rd.Read()) {
ListViewItem lvvi = new ListViewItem(rd.GetString(0));
lvvi.SubItems.Add(rd.GetString(1));
lvvi.SubItems.Add(rd.GetString(5));
lvvi.SubItems.Add("1");
lvvi.SubItems.Add(rd.GetString(0));
int listViewItemID;
int[] ids;
ids = new int[100];
if (listView3.Items.Count > 0)
{
int addingItemID;
//ADD ListView ids into array
int i=0;
foreach (ListViewItem li in listView3.Items)
{
listViewItemID = Int32.Parse(li.SubItems[0].Text);
addingItemID = Int32.Parse(rd.GetString(0));
ids[i] = listViewItemID;
i++;
}
//Check item allready exsist
if (ids.Contains(Int32.Parse(rd.GetString(0))))
{
MessageBox.Show("sdsd");
}
else {
listView3.Items.Add(lvvi);
}
}
else {
listView3.Items.Add(lvvi);
}
}
//Calculate Price summery
this.calculatePrice();
Instead of looping to get all id's, you can loop through the items or use linq to find the specific id and keep the result. This can be done in an external function or by replacing the ids portion with the loop or use something like FirstOrDefault:
addingItemID = rd.GetString(0);
ListViewItem existing = listView3.Items.Cast<ListViewItem>().FirstOrDefault(li => li.SubItems[0].Text == addingItemID); //(not sure if the cast is needed)
if (existing != null)
{
//item exists, variable existing refers to the item
MessageBox.Show("sdsd");
}
else
{
listView3.Items.Add(lvvi);
}

How to retrieve if an item in a CheckedListBox is checked or not? Winforms C#

I have a foreach() statement running through all items inside a CheckedListBox.
How can I know if a item is or not checked?
If useful here's the code:
foreach (object user in checkedListBoxUsersWhoSee.Items)
{
// Privileged = if the user is checked he has privileges;
alias = user.ToString().Substring(user.ToString().Length - 3);
SelectUserID = new SqlCommand(Properties.Resources.SelectUserID + alias, TeamPWSecureBD);
userIDAuth = (int)SelectUserID.ExecuteScalar();
InsertAuths.Parameters.AddWithValue("#idPass", idPass);
InsertAuths.Parameters.AddWithValue("#idUser", userIDAuth);
InsertAuths.Parameters.AddWithValue("#Privileged", idPass);
//Code not finished
}
for (int i = 0; i < checkedListBoxUsersWhoSee.Items.Count; i++)
{
CheckState checkState = checkedListBoxUsersWhoSee.GetItemCheckState(i);
//CheckState.Checked
//CheckState.Indeterminate
//CheckState.Unchecked
}
You can use this code :
foreach (object user in checkedListBox.Items)
{
bool Privileged = checkedListBox.GetItemCheckState(checkedListBox.Items.IndexOf(user)) == CheckState.Checked;
}
try
foreach (CheckBox user in checkedListBox1.CheckedItems)
{
}
CheckedListBox has a property CheckedItems which is a collection of the checked or indeterminate items.
var items = checkedListBoxUsersWhoSee.CheckedItems;
UPDATE
I tested adding items to a CheckedListBox and they did not appear under the CheckedItems property suggesting that by default they are initialized with the value Unchecked.
#Arvin had given the right answer but idkw he edited to a more confuse way of solving the problem.
The code below is working like a charm so please to the person who edited the correct answer stop messing around.
foreach (object user in checkedListBoxUsersWhoSee.Items)
{
Privileged = checkedListBoxUsersWhoSee.CheckedItems.Contains(user);
...
}
I used the following:
ArrayList selected = new ArrayList();
for (int i = 0; i < chkRoles.Items.Count; i++) //chkRoles being the CheckBoxList
{
if (chkRoles.GetItemChecked(i))
selected.Add(chkRoles.Items[i].ToString()); //And I just added what was checked to the Arraylist. String values
}
Easiest way:
foreach(ListItem item in checkedListBoxUsersWhoSee.Items){
if (item.Selected){
// LOGIC HERE
}
}

c# loop listbox selected items

I have a listbox on a form set to allow multiple selections. I want to loop through each selected item, store the selected value in a variable and do some work. I've tried many different variations of code to do this, but so far nothing has worked. Any help would be greatly appreciated! My code is below:
foreach (var item in systemList.Items)
{
string systemName = systemList.SelectedItems.ToString();
//do some work//
}
You can get all SelectedItems using below code:
var items = systemList.Items.Cast<ListItem>().Where(item => item.Selected);
You can then loop through the items
foreach (var item in items)
{
//Access value of each item by calling item.Value
}
foreach (var item in systemList.SelectedItems)
{
string systemName = item.ToString();
//do some work//
}
make sure listbox Selection mode is set to other than single!

How do I find out if individual items in CheckedListBox are checked? C#

I've tried looking in checkedListBox1.Items, but that didn't help. So how do I check if an item in a CheckedListBox is marked? It's in a windows forms application.
You can get a list of checked items using CheckedItems property.
Example 1:
foreach (var item in this.checkedListBox1.CheckedItems)
{
MessageBox.Show(item.ToString());
}
Example 2:
this.checkedListBox1.CheckedItems.Cast<object>()
.ToList()
.ForEach(item =>
{
//do stuff here
//for example
MessageBox.Show(item.ToString());
});
If you are sure items are string for example, you can use Cast<object> in above code.
You can get the list of checked indices using CheckedIndices property.
Example:
this.checkedListBox1.CheckedIndices.Cast<int>()
.ToList()
.ForEach(index =>
{
//do stuff here
//for example
MessageBox.Show(this.checkedListBox1.Items[index].ToString());
});
try this:
foreach (ListItem item in checkedListBox1.Items)
{
if (item.Selected)
{
// If the item is selected
}
else
{
// Item is not selected, do something else.
}
}

c# Is there a option to filter a listbox

I want to know if there is a possibility to filter a listbox. I mean it in such a way that is i add an item and the name is already in the listbox that you get a messagebox.show that tells you"Item already in the listbox". And that it won't be added twice.
You don't need to iterate throug the items as the Items collection of the ListBox implements the "Contains" method.
if (listBox1.Items.Contains(Item))
{
MessageBox.Show("ListBox already contains Item");
}
"Item" is in this case the Item from the other ListBox
Update. You could write:
if (listBox1.Items.Contains(listBox2.SelectedItem))
{
MessageBox.Show("ListBox already contains Item");
}
else
{
listBox1.Items.Add(listBox2.SelectedItem);
}
Use data binding might be one of the solutions:
List<string> SomeData=...
var filtered=SomeData.Where(...); // <-- Your filtering condition here
listBox1.DataSource = new BindingSource(choices, null);
Inside the event/method which adds list items inside your listbox you can add something like:
// search for list item in the listbox which has the text
ListItem li = theListBox.Items.FindByText("yourListItemName");
if (li != null)
{
// if list item exists display message
MessageBox.Show("ListBox already contains item with the name");
}
else
{
theListBox.Items.Add("yourListItemName");
}
here is a sample code try and implement it in you code
ListBox.ObjectCollection ListItem1= ListBox1.Items;
if(!string.IsNullOrEmpty(SearchBox.Text))
{
foreach (string str in ListItem1)
{
if (str.Contains(SearchBox.Text))
{
msgbox;
}
}
}

Categories