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
}
}
Related
I have a set of RadioButtons in a repeater. Once a RadioButton is checked, the related repetition is determined in a loop through its items and a parameter is saved to a Data Base. This triggers the loading of the next question with a new set of RadioButtons is. So far so good.
If the user navigates back to the previous question then he could post a new selection and mess up everything. To deal with this unwanted operation, I wrote this code for the RadioButton OnChecked event:
All repeaters Radio Buttons are first set back to unchecked and then the latest selection restored with ((RadioButton)sender).Checked = true.
Afterwards I determine the related parameter and overwrite the already existing record for that question with the new value.
protected void RB_Checked(object sender, EventArgs e)
{
for (int i = 0; i <= RPT_DisplayInquiry.Items.Count - 1; i++)
{
RadioButton rb = (RadioButton)RPT_DisplayInquiry.Items[i].FindControl("RB_Choice");
rb.Checked = false;
}
((RadioButton)sender).Checked = true;
for (int i = 0; i <= RPT_DisplayInquiry.Items.Count - 1; i++)
{
RadioButton rb = (RadioButton)RPT_DisplayInquiry.Items[i].FindControl("RB_Choice");
if (rb.Checked == true)
{
try
{
string Choice = Convert.ToString(i + 1);
Label lbl = (Label)RPT_DisplayInquiry.Items[i].FindControl("Lbl_Structure");
SaveSelection(lbl.Text, Choice, 0);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
For some reason this doesn't work. If I navigate back again after the new selection is saved, I see that the reset had not worked and that 2 RadioButtons are selected. Therefore the saved value is not necessarily correct as it is just related to the first found checked RadioButton in the repeater.
If I eliminate the call of the Save Routine from that methode and call it afterwards from a separate click event then the whole thing works.
Does the reset of the RadioButton not work as they are never rendered?
What is going on?
I recently changed my form to use toolStripMenuItems to execute processes instead of buttons. I bound the the existing btnWhatever_Click() to the Menu Item's Click event.
I have a single column of checkboxes to select which rows to process. The last checkbox I click on is visibly checked, but is ignored as if it isn't when I run the processing from the menu instead of the button. Before processing, I always count the number of checks to make sure the user knows how many rows they are processing. It is always 1 less than it should be.
private int countApprovalChecks()
{
//count approval check marks
int ctr = 0;
foreach (DataGridViewRow row in dgvAppManualReviewMatches.Rows)
{
if (Convert.ToBoolean(row.Cells[chkApprove.Name].Value) == true)
{
ctr++;
}
}
return ctr;
}
What am I missing?
I'm guessing your grid is still in edit mode, which would affect the value of the row:
private int countApprovalChecks()
{
dgvAppManualReviewMatches.EndEdit();
//count approval check marks
int ctr = 0;
foreach (DataGridViewRow row in dgvAppManualReviewMatches.Rows)
{
if (Convert.ToBoolean(row.Cells[chkApprove.Name].Value) == true)
{
ctr++;
}
}
return ctr;
}
When you had your code in the button, it would take the focus away from the grid, ending the edit mode, but your menu item does not take away the focus, so your edit mode is still continuing.
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;
}
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;
}
As I have check box in gridview if i dont select any one checkbox and if i click asp button then i have to show message to user to select checkbox
awaiting response
Should be something like you need...
Boolean Selected = false;
for (int count = 0; count < grd.Rows.Count; count++)
{
if (((CheckBox)grd.Rows[count].FindControl("yourCheckbox")).Checked)
{
Selected = true;
}
}
if (Selected == false)
{
//your message goes here.
}
if you need javascript code...
function CheckIfSelect() {
var frm = document.forms[0];
var Selected=false;
for (i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].type == "checkbox") {
if(frm.elements[i].checked)
{
Selected=true;
break;
}
}
if(Selected==false)
{
//your message goes here
}
}
}
If you want to do this client side you could use a library like jQuery to iterate through the checkboxes.
If you want to do this server side, you will need to reenumerate the controls on postback, and check the Checked value. Alternatively if this GridView binds to a DataSource, check the posted back values within the DataSource.