Iterate through CheckedListBox in WinForms? - c#

If I have Checked list box in Win forms which I fill like this
List<Tasks> tasks = db.GetAllTasks();
foreach (var t in tasks)
tasksCheckedListBox.Items.Add(t.Name);
How can I iterate tasksCheckedListBox.Items and set some check boxes as checked?
Thanks

The add method takes an optional IsChecked parameter. You can then add your objects into the checked list box in the correct state.
List<Tasks> tasks = db.GetAllTasks();
foreach (var t in tasks)
tasksCheckedListBox.Items.Add(t.Name, isChecked);
Or you can change the checked state of an item after you add it with something like this:
foreach(var task in tasks)
{
tasksCheckedListBox.SetItemChecked(clb.Items.IndexOf(task), isChecked);
}

If you want to do it after the items have been added, there is an example on MSDN
Copied here:
private void CheckEveryOther_Click(object sender, System.EventArgs e) {
// Cycle through every item and check every other.
// Set flag to true to know when this code is being executed. Used in the ItemCheck
// event handler.
insideCheckEveryOther = true;
for (int i = 0; i < checkedListBox1.Items.Count; i++) {
// For every other item in the list, set as checked.
if ((i % 2) == 0) {
// But for each other item that is to be checked, set as being in an
// indeterminate checked state.
if ((i % 4) == 0)
checkedListBox1.SetItemCheckState(i, CheckState.Indeterminate);
else
checkedListBox1.SetItemChecked(i, true);
}
}
insideCheckEveryOther = false;
}

Related

Deleting multiple checked items from an SQL bound checklist

So right now, I have tried the following code, however it only removes one list item. It seems that after it deletes the first item, the list refreshes and the other checked item does not get deleted. How can I go around this so that all the checked items are deleted from the DB Table?
//NewFoodInputTextBox is an ASP.NET TextBox which takes input
//just fine and outputs status/error updates as well.
protected void DeleteFoodButton_Click(object sender, EventArgs e)
{
try
{
int delCount = 0;
int prevDelCount = 0;
string status = "";
foreach (ListItem Item in FoodChecklist.Items)
{
if (Item.Selected)
{
FoodList.Delete(); //only deletes 1 item
prevDelCount = delCount;
delCount += 1;
if (delCount > prevDelCount) //printing out the deleted items
{
status = status + " " + Item.ToString(); //returns all checked items normally
}
}
}
if (delCount == 0)
{
NewFoodInputTextBox.Text = "Nothing selected to delete";
}
else
{
NewFoodInputTextBox.Text = "Deleted the following: " + status;
}
}
catch
{
NewFoodInputTextBox.Text = "Unexpected behavior detected";
}
}
Your problem is that you are using the Selected items, and not the Checked ones. These are 2 different things (selected is the blue highlight, checked is the checkbox). Use the Checked property in your condition and everything should work fine.
Side note, you could also use the CheckedItems property of the ListView in your foreach to simplify your code.
foreach (ListItem Item in FoodChecklist.CheckedItems)

CheckedListBox Only One Checked But Keep Last

I am having some difficulty getting a CheckedListBox to behave the way I want it to. What I am trying to accomplish is getting a CheckedListBox with the first box checked on PageLoad. I want only one checkbox checked at any given time but I also don't want the user to uncheck the last checked box. I can do one or the other but I can't seem to do both.
Here is some code snippets that I have used to accomplish the task of having only one checkbox checked. The problem with these are the last selection can be unchecked where there are no checkboxes checked.
1st Snippet:
if(e.NewValue == CheckState.Checked)
{
// Uncheck the other items
for (int i = 0; i < defCheckedListBox.Items.Count; i++)
{
if (e.Index != i)
{
this.defCheckedListBox.SetItemChecked(i, false);
}
}
}
2nd Snippet
// Ensure that we are checking an item
if (e.NewValue != CheckState.Checked)
{
return;
}
// Get the items that are selected
CheckedListBox.CheckedIndexCollection selectedItems = this.defCheckedListBox.CheckedIndices;
// Check that we have at least 1 item selected
if (selectedItems.Count > 0)
{
// Uncheck the other item
this.defCheckedListBox.SetItemChecked(selectedItems[0], false);
}
Here is what I have used to prevent the last checked box to be "unchecked"
if (laborLevelDefCheckedListBox.CheckedItems.Count == 1)
{
if (e.CurrentValue == CheckState.Checked)
{
e.NewValue = CheckState.Checked;
}
}
I know this has got to be simple but I think because I've had a long week and I have looked at this too long it is just not coming to me. Any help with this is super appreciated! If I solve this over the weekend I will be sure to post my solution. BTW Happy Holidays to those here in the States :)
Chris makes a good point in the comments that this feels like you are re-inventing radio buttons but you are almost there with the code you have posted if you really want it to work with a CheckedListBox. I have adapted the code from your 1st Snippet which I think does the trick:
//remove the event handler so when we change the state of other items the event
//isn't fired again.
defCheckedListBox.ItemCheck -= defCheckedListBox_ItemCheck;
if (e.NewValue == CheckState.Checked)
{
// Uncheck the other items
for (int i = 0; i < defCheckedListBox.Items.Count; i++)
{
if (e.Index != i)
{
this.defCheckedListBox.SetItemChecked(i, false);
}
}
}
else
{
//the state was not checked.
//as only one item can ever be Checked inside the event
//handler the state of not checked is invalid for us; set the state back to Checked.
e.NewValue = CheckState.Checked;
}
//re-add the event handler
defCheckedListBox.ItemCheck += defCheckedListBox_ItemCheck;
Essentially the only new parts are the else where we reset the state if the state was not Checked and the removing and re-adding of the event to prevent it firing again when we manually set the state of other items (this could be handled with a global bool if you prefer).
// Use CheckBoxList Event
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
// Stops DeInitialize Event
checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
// Get the new value old value my be in Indeterminate State
checkedListBox1.SetItemCheckState(e.Index, e.NewValue);
// Start ReInitialize Event
checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}

How to set radio.IsChecked = true; to a particular radiobutton programatically using c#

I am working on silverlight and i have created a radiobutton i want to set manually the check of radiobutton programatically to the given 3 items (itms means 3 radiobutton) on radio button.I tried like this
RadioButton radio = new RadioButton();
suppose this radio buttons contains " items( radio buttons) and when i try the code below to check the second item (out of 3 items) the code below checks the last item.
radio.Loaded += (p, q) =>
{
radio.IsChecked = true;
};
How i create button is :
foreach (String item in param.Component.Attributes[0].Item)
{
radio = new RadioButton()
{
Content = item,
GroupName = "MyRadioButtonGroup",
Tag = tg
};
radio.Checked += (o, e) =>
{
//Do something
};
sp.Children.Add(radio);
count++; tg++;
}
Why checks the last item ? How to check the second item programatically usin silverlight in c# code?
I try to do so because i want to intialise the radio button after the program launch (before button clicks) because on before button click of radio buttons if i try to print the itmes on text block, I see nothing (it only show on button clicks but i want something displayed before clicking instead of empty space)
The short answer to your question is that you set radio.IsChecked=truein the code to make the RadioButton checked.
One way to solve this is to set IsChecked = true when the second radio button is added. Since your code is in a foreach loop your count variable should work.
foreach (String item in param.Component.Attributes[0].Item)
{
radio = new RadioButton()
{
Content = item,
GroupName = "MyRadioButtonGroup",
Tag = tg
};
radio.Checked += (o, e) =>
{
//Do something
};
sp.Children.Add(radio);
count++; tg++;
if (count == 2){
radio.IsChecked=true;
}
}
Or you could change your foreach loop to a for loop
for (int i = 0; i < param.Component.Attributes[0].Item.Count ; i++)
{
}
if (i== 2){
radio.IsChecked=true;
}
While both these approaches work they don't mesh well with the databound approach common in most Silverlight applications. The initial state of the selected items should really be stored in a state variable.

Adding items to List<> of object which already contain data, add duplicate item in the List

I am developing a Windows phone app for which I want to get a list of first 15 object from my web service plus an extra item to represent the "Load next 15 items button" and bind it to a listbox. On selection of the last element or index(buttton), I want to remove the last item(button) from the list and call the service again to get the next 15 items plus the button item which will again add up to the current list without clearing the list. And the same process goes on as we select the last item from the listbox.
My problem is I am able to get it correctly for the first round. In the second round, the next 15 element is added to the list twice. I don't know what is the real problem. I am not getting any error or exception also.
Below is what I have done so far :
private void ListBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int LastIndex=app.imgItem.Count - 1;
if (ListBox1.SelectedIndex == LastIndex)
{
app.imgItem.Remove(app.imgItem[app.imgItem.Count-1]);
proxy.SelectNextItemsCompleted += new EventHandler<ServiceReference1.SelectNextItemsCompletedEventArgs>(proxy_SelectNextItemsCompleted);
int id = app.imgItem.Last().Id;
proxy.SelectNextItemsAsync(categoryID, id);
}
}
void proxy_SelectNextItemsCompleted(object sender, ServiceReference1.SelectNextItemsCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show("Cannot load data.");
return;
}
else
{
foreach (var item in e.Result)
{
ImgData idata = new ImgData();
idata.CategoryID = item.CategoryID;
idata.ImageID = item.ImageID;
idata.ImageTitle = item.ImageTitle;
idata.Thumbnail = item.Thumbnail;
app.imgItem.Add(idata);
}
}
ImageData btnData = new ImageData();
btnData.CategoryID = 0;
btnData.ImageID = 0;
btnData.ImageTitle = "";
btnData.Thumbnail = "Images/loadButton.jpg";
app.imgItem.Add(btnData);
ListBox1.ItemsSource = app.imgItem;
}
It looks like you're re-registering an event handler in the SelectionChanged event handler, and as a result, the SelectNextItemsCompleted handler is probably getting called twice the second time around:
proxy.SelectNextItemsCompleted += new EventHandler<ServiceReference1.SelectNextItemsCompletedEventArgs>(proxy_SelectNextItemsCompleted);
You should probably be registering that event handler somewhere else where the code only runs once.

ViewState to compare CheckBoxList Selected Values

I have a button that creates a CheckBoxList. The items in the CheckBoxList are selected based on a user's current notification subscriptions. I'm storing the true or false value of the selected item.
After the users change their subscriptions by checking or unchecking a box in the CheckBoxList, they click another button to update their notification subscriptions. I need to compare the Viewstate["PREV"] with the changed selections on postback and run some functions based on the changes.
ArrayList list = new ArrayList();
for (int i = 0; i < checkBoxList1.Items.Count; i++)
{
list.Add(checkBoxList1.Items[i].Selected.ToString());
}
ViewState["PREV"] = list;
Even though I can't see the values with a Response.Write, the values for the ViewState are correct when I add a watch in debug.
The problem I'm having is how to approach the next step to do the comparison. This is what I want to accomplish:
for (int i = 0; i < checkBoxList1.Items.Count; i++)
{
//if checkbox state goes from false to true, subscribe to topic
//mySubscribeMethod
//else if checkbox state goes from true to false, unsubscribe to topic
//myUnsubscribeMethod
//else if checkbox state is unchanged, do nothing
}
You can try something like this
ArrayList list = ViewState["PREV"] as ArrayList;
for (int i = 0; i < checkBoxList1.Items.Count; i++)
{
if (checkBoxList1.Items[i].Selected == true && Convert.ToBoolean(list[i]) == false)
{
// Subscribe Method
}
if (checkBoxList1.Items[i].Selected == false && Convert.ToBoolean(list[i]) == true)
{
// Unsubscribe Method
}
else
{
// Continue to loop
}
}

Categories