How to check CheckListBox item with single click? - c#

I am coding Windows Forms application in C# and using CheckListBox Control.
How to check CheckListBox item with just single click?

I think you are looking for
CheckOnClick property
set it to true
Gets or sets a value indicating
whether the check box should be
toggled when an item is selected.

Set the property at Design Time in this way
or by code:
CheckedListBox.CheckOnClick = true;

I just finished working through an issue where I had set CheckOnClick to True via the designer, but the UI was still requiring a second click to check items. What I found is that for whatever reason, the designer file was not updating when I changed the value. To resolve, I went into the designer file and added a line
this.Product_Group_CheckedListBox.CheckOnClick = true;
After this, it worked as expected. Not sure why the designer didn't update, but maybe this workaround will help someone.

You can also use a check box exterior to the CheckListBox to check/uncheck all items. On the same form add a checkbox near the CheckedListBox and name it CkCheckAll. Add the Click event for the CheckBox (which I prefer to the CheckChanged event).
There is also a button (BtnAdd) next to the CheckedListBox which will add all checked items to a database table. It is only enabled when at least one item in the CheckedListBox is checked.
private void CkCheckAll_Click(object sender, EventArgs e)
{
CkCheckAll.Text = (CkCheckAll.Checked ? "Uncheck All" : "Check All");
int num = Cklst_List.Items.Count;
if (num > 0)
{
for (int i = 0; i < num; i++)
{
Cklst_List.SetItemChecked(i, CkCheckAll.Checked);
}
}
BtnAdd_Delete.Enabled = (Cklst_List.CheckedItems.Count > 0) ? true : false;
}

you can also check all by button click or click on checklist
private void checkedListBox1_Click(object sender, EventArgs e)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
checkedListBox1.SetItemChecked(i, true);
}

Related

How to deal with a change of Radio Button selection after navigating back?

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?

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 check whether gridview's row is selected or not in c#.net windows application

I want to know how to check whether a gridview's row got selected or not.
I am working on windows application.
I want to put a if condition ie if a particular row gets selected then fill the textbox with the correspoding cell value.
I am just not getting the way how to give the condition in the if clause.
Handle the DataGridView.SelectionChanged event. Use the DataGridView.SelectedRows property to get the selected rows collection.
private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
// Update the text of TextBox controls.
textBox1.Text = dataGridView.SelectedRows[0].Cells[1].Value.ToString();
textBox2.Text = dataGridView.SelectedRows[0].Cells[2].Value.ToString();
....
}
Check DataGridViewRow.Selected property.
if (dataGridView.Rows[rowIndex].Selected)
{
// Do something ..
}
Check the selected property of DataGridViewRow, it returns true for selected else false.
bool isSelected = dataGridView1.Rows[e.RowIndex].Selected;
You can subscribe to the SelectionChanged event of the control and iterate through each selected row if multi-selection is enabled or just the first one if single-row selection only.
private void MyGridView_SelectionChanged(object sender, EventArgs e)
{
for (int i = 0; i < MyGridView.SelectedRows.Count; i++)
{
MyTextBox.Text = MyGridView.SelectedRows[i].Cells[0].Value.ToString(); //assuming column 0 is the cell you're looking for
// do your other stuff
}
}
More information can be found on the SelectedRows property.

ListBox and Datasource - prevent first item from being selected

Hey. I've got the following code that populates my list box
UsersListBox.DataSource = GrpList;
However, after the box is populated, the first item in the list is selected by default and the "selected index changed" event fires. How do I prevent the item from being selected right after the list box was populated, or how do I prevent the event from firing?
Thanks
To keep the event from firing, here are two options I have used in the past:
Unregister the event handler while setting the DataSource.
UsersListBox.SelectedIndexChanged -= UsersListBox_SelectedIndexChanged;
UsersListBox.DataSource = GrpList;
UsersListBox.SelectedIndex = -1; // This optional line keeps the first item from being selected.
UsersListBox.SelectedIndexChanged += UsersListBox_SelectedIndexChanged;
Create a boolean flag to ignore the event.
private bool ignoreSelectedIndexChanged;
private void UsersListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (ignoreSelectedIndexChanged) return;
...
}
...
ignoreSelectedIndexChanged = true;
UsersListBox.DataSource = GrpList;
UsersListBox.SelectedIndex = -1; // This optional line keeps the first item from being selected.
ignoreSelectedIndexChanged = false;
Well, it looks like that the first element is automatically selected after ListBox.DataSource is set. Other solutions are good, but they doesn't resolve the problem. This is how I did resolve the problem:
// Get the current selection mode
SelectionMode selectionMode = yourListBox.SelectionMode;
// Set the selection mode to none
yourListBox.SelectionMode = SelectionMode.None;
// Set a new DataSource
yourListBox.DataSource = yourList;
// Set back the original selection mode
yourListBox.SelectionMode = selectionMode;
i using the following, seems to work for me:
List<myClass> selectedItemsList = dataFromSomewhere
//Check if the selectedItemsList and listBox both contain items
if ((selectedItemsList.Count > 0) && (listBox.Items.Count > 0))
{
//If selectedItemsList does not contain the selected item at
//index 0 of the listBox then deselect it
if (!selectedItemsList.Contains(listBox.Items[0] as myClass))
{
//Detach the event so it is not called again when changing the selection
//otherwise you will get a Stack Overflow Exception
listBox.SelectedIndexChanged -= listBox_SelectedIndexChanged;
listBox.SetSelected(0, false);
listBox.SelectedIndexChanged += listBox_SelectedIndexChanged;
}
}
set IsSynchronizedWithCurrentItem="False" and Also SelectedIndex=-1 and every thing should work for you
If you just want to clear the selected value, you can use ClearSelected after you set the DataSource. But if you dont want the event to fire, then you'll have to use one of Joseph's methods.
Perhaps in DataSourceChanged you could check the state of SelectedIndex, if your lucky you could then just force SelectedIndex = -1.

CheckedListBox Control - Only checking the checkbox when the actual checkbox is clicked

I'm using a CheckedListBox control in a small application I'm working on. It's a nice control, but one thing bothers me; I can't set a property so that it only checks the item when I actually check the checkbox.
What's the best way to overcome this?
I've been thinking about getting the position of the mouseclick, relative from the left side of the checkbox. Which works partly, but if I would click on an empty space, close enough to the left the current selected item would still be checked. Any ideas regarding this?
I know this thread's a bit old, but I don't think it's a problem to offer another solution:
private void checkedListBox1_MouseClick(object sender, MouseEventArgs e)
{
if ((e.Button == MouseButtons.Left) & (e.X > 13))
{
this.checkedListBox1.SetItemChecked(this.checkedListBox1.SelectedIndex, !this.checkedListBox1.GetItemChecked(this.checkedListBox1.SelectedIndex));
}
}
(With the value of CheckOnClick = True).
You could use that thingy with the rectangle, but why make it more complex the it needs to.
Well, it is quite ugly, but you could calculate mouse hit coordinates against rectangles of items by hooking on CheckedListBox.MouseDown and CheckedListBox.ItemCheck like the following
/// <summary>
/// In order to control itemcheck changes (blinds double clicking, among other things)
/// </summary>
bool AuthorizeCheck { get; set; }
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if(!AuthorizeCheck)
e.NewValue = e.CurrentValue; //check state change was not through authorized actions
}
private void checkedListBox1_MouseDown(object sender, MouseEventArgs e)
{
Point loc = this.checkedListBox1.PointToClient(Cursor.Position);
for (int i = 0; i < this.checkedListBox1.Items.Count; i++)
{
Rectangle rec = this.checkedListBox1.GetItemRectangle(i);
rec.Width = 16; //checkbox itself has a default width of about 16 pixels
if (rec.Contains(loc))
{
AuthorizeCheck = true;
bool newValue = !this.checkedListBox1.GetItemChecked(i);
this.checkedListBox1.SetItemChecked(i, newValue);//check
AuthorizeCheck = false;
return;
}
}
}
Another solution is to simply use a Treeview.
Set CheckBoxes to true, ShowLines to false, and ShowPlusMinus to false and you have basically the same thing as a CheckedListBox. The items are only checked when the actual CheckBox is clicked.
The CheckedListBox is much more simplistic, but the TreeView offers a lot of options that can potentially be better suited for your program.
I succesfully used this property:
CheckedBoxList.CheckOnClick
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.checkedlistbox.checkonclick?view=netframework-4.7.2
The text for a checkbox in a CheckedListBox is rendered by default is to place an HTML label after the checkbox input and set the label's "for" attribute to the ID of the checkbox.
When a label is denoting an element that it is "for," clicking on that label tells the browser to focus on that element, which is what you're seeing.
Two options are to render your own list with separate CheckBox controls and text (not as the Text property of the CheckBox, as that does the same thing as the CheckBoxList) if the list is static or to use something like a Repeater if the list is dynamic.
Try this. Declare iLastIndexClicked as a form-level int variable.
private void chklst_MouseClick(object sender, MouseEventArgs e)
{
Point p = chklst.PointToClient(MousePosition);
int i = chklst.IndexFromPoint(p);
if (p.X > 15) { return; } // Body click.
if (chklst.CheckedIndices.Contains(i)){ return; } // If already has focus click anywhere works right.
if (iLastIndexClicked == i) { return; } // native code will check/uncheck
chklst.SetItemChecked(i, true);
iLastIndexClicked = i;
}
Just checking to see if the user clicked in the leftmost 15 pixels of the checked list (the check box area) works at all times except re-checking a currently selected item. Storing the last index and exiting without changing lets the native code handle that properly, trying to set it to checked in that case turns it on and it just turns back off when the "ItemCheck" code runs.

Categories