checkbox/toggle button check/uncheck itself - c#

I have a number of checkboxes that I want to handle them as toggle buttons. Each one is totally independent from the other and can be either checked or unchecked. When the user clicks on the checkbox/button it stays checked and if the user clicks again, then the checkbox/button returns to the "unchecked" state. Can the checkbox/button check/uncheck itself?
I have been trying for a long time, searching also in the internet and cannot find a solution.

Check the status of the check box, every time the button is clicked, change it.
private void toggButton_CheckedChanged(object sender, EventArgs e)
{
// everytime you click the button checkbox states will change.
if(checkBox.Checked)
{
checkBox.Checked = false;
}
else
{
checkBox.Checked = true;
}
}

The problem is that the checkbox/button is "displayed" as always
pressed i.e. the "blue" color that it has when checked is not changed
giving the impression that it is not unchecked. – user1304490
May be setting CheckBox.ThreeState property false helps.
If the ThreeState property is set to false, the CheckState property value can only be set to the Indeterminate value of System.Windows.Forms.CheckState in code and not by user interaction.

A very short command:
checkBox.Checked = !checkBox.Checked;

You can assign a common event to all Checkboxes. Write this code in your .cs file and select all Checkboxes and assign this event to checkedChange event.
private void chkboxes_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if(!chk.Checked)
chk.Checked = true;
else
chk.Checked = false;
}

Ref: CheckBox.CheckState property.
it is read and write property so you set it in GUI or through code.
Checked The CheckBox displays a check mark. The control appears sunken.
Unchecked The CheckBox is empty. The control appears raised.
Indeterminate The CheckBox displays a check mark and is shaded. The control appears flat.
write this on checked change event and check it is toggle or not.. it will work as like a switch..
label1.Text = "ThreeState: " + checkBox1.ThreeState.ToString() + "\n" + "Checked: " +
checkBox1.Checked.ToString() + "\n" + "CheckState: " + checkBox1.CheckState.ToString();
for your question's answer check CheckBox.AutoCheck Property

When you want to change check box state for too many check boxes on one form, you need fast reliable code, without complexity.
The best way for doing it is using:
CheckBox.CheckState
you can change Check Boxes state to (unchecked) for example using this code:
checkbox1.CheckState = CheckState.Unchecked;
checkbox2.CheckState = CheckState.Unchecked;
checkbox3.CheckState = CheckState.Unchecked;
For further reading, see this from MSDN.

The question is very unclear but if someone is still struggling with checkboxes:
Toggle between two of them(both checkboxes cannot be ticked at the same time and min. one need to be ticked):
private void chkBoxON_CheckedChanged(object sender, EventArgs e)
{
if (chkBoxON.Checked)
{
chkBoxOFF.Checked = false;
// here some code to do after this checkbox is ticked
}
else
{
chkBoxOFF.Checked = true;
}
}
private void chkBoxOFF_CheckedChanged(object sender, EventArgs e)
{
if (chkBoxOFF.Checked)
{
chkBoxON.Checked = false;
// here some code to do after this checkbox is ticked
}
else
{
chkBoxON.Checked = true;
}
}
If you need only one checked or both unchecked then:
if (chkBoxON.Checked)
{
chkBoxOFF.Checked = false;
}
}
private void chkBoxOFF_CheckedChanged(object sender, EventArgs e)
{
if (chkBoxOFF.Checked)
{
chkBoxON.Checked = false;
}
If you need to change the state of it using the button then:
private void button1_Click(object sender, EventArgs e)
{
chkBoxON.Checked = false;
//chkBoxON.Checked = true; //if need to be checked
}
If you need to disable the possibility to click checkBox then:
chkBoxOFF.Enabled = false;

You just need to use the NOT operator to create the simplest toggle.
checkBox.Checked = !checkBox.Checked;

Related

C# datagridview two checkboxes columns act like two radio buttons

i'm developing an application using c# i've add two checkboxes in the datagridview. i want them to act like two radio buttons. if first checkbox is checked the other one is unchecked automatically
i tried some code but did't work for me.
private void datagridSB_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 15)
{
if (Convert.ToBoolean(datagridSB.CurrentRow.Cells[15].Value)==true)
{
datagridSB.CurrentRow.Cells[17].Value = false;
//uncheck the second checkbox
}
else if (Convert.ToBoolean(datagridSB.CurrentRow.Cells[15].Value)==false)
{
datagridSB.CurrentRow.Cells[17].Value = true;
//check the second checkbox
}
}
if (e.ColumnIndex == 17)
{
if (Convert.ToBoolean(datagridSB.CurrentRow.Cells[17].Value) == true)
{
datagridSB.CurrentRow.Cells[15].Value = false;
//uncheck the first checkbox
}
else if (Convert.ToBoolean(datagridSB.CurrentRow.Cells[17].Value) == false)
{
datagridSB.CurrentRow.Cells[15].Value = true;
//check the first checkbox
}
}
}
i get the error NullReferenceException was un handled (object reference not set to an instance of an object)
any help please
I can't believe I missed it, sec... You are converting to bool the entire condition:
Convert.ToBoolean(datagridSB.CurrentRow.Cells[17].Value = true)
move the end paren to after the value, and == not "=" in C# so:
Convert.ToBoolean(datagridSB.CurrentRow.Cells[17].Value) == true
Your code is setting the value, and evaluating your boolean off the set...
I still do not understand why you want to use two check boxes when one appears to be all that is needed. The problem you may run into is twofold. First, using the CurrentRow property of the DataGridView is risky, it may return unexpected results and I feel this may be one of the problems. The other issue is using the CellValueChanged event to capture when the user changes one of the check boxes. This event appears to return false in some cases when the check box is checked. Because of this odd behavior, I am guessing the CellValueChanged event is not the best for what you want to do.
To remedy these two issues, I recommend you use the RowIndex returned from the event instead of the CurrentRow property. Also, the event we want to change to is the CellContentClick event. This event will fire when the user clicks into the content of a cell. In the case of the check box cells, this will change its value from checked to un-checked and vice versa. Here we simply need to check if the check box is checked. If it is checked, then set the other check box to un-checked and vice –versa.
The code below demonstrates what is described above. There is a DataGridView with three columns, the last two columns are check boxes. The CellContentClick event is wired up to capture when the content of a cell is clicked then we simply check to see if the cell clicked is in columns 1 or 2, then set the other check box appropriately. I added the CellContentDoubleClick event to call the CellContentClick event, otherwise the user would be able to quickly double click on a check box and not give time for the other checkbox to get set, resulting in both check boxes with the same value.
private void datagridSB_CellContentClick(object sender, DataGridViewCellEventArgs e) {
int curRow = e.RowIndex;
if (e.ColumnIndex == 1) {
DataGridViewCheckBoxCell cbc = datagridSB.Rows[curRow].Cells[1] as DataGridViewCheckBoxCell;
bool isChecked = (bool)cbc.EditedFormattedValue;
if (isChecked) {
datagridSB.Rows[curRow].Cells[2].Value = false;
} else {
datagridSB.Rows[curRow].Cells[2].Value = true;
}
}
if (e.ColumnIndex == 2) {
DataGridViewCheckBoxCell cbc = datagridSB.Rows[curRow].Cells[2] as DataGridViewCheckBoxCell;
bool isChecked = (bool)cbc.EditedFormattedValue;
if (isChecked) {
datagridSB.Rows[curRow].Cells[1].Value = false;
} else {
datagridSB.Rows[curRow].Cells[1].Value = true;
}
}
}
private void datagridSB_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) {
datagridSB_CellContentClick(sender, e);
}
Hope this helps.
private void datagridSB_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (datagridSB.Columns[e.ColumnIndex].Name == "withCashSB")
{
DataGridViewCheckBoxCell buttonCell = (DataGridViewCheckBoxCell)datagridSB.Rows[e.RowIndex].Cells["withProCSB"];
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)datagridSB.Rows[e.RowIndex].Cells["withCashSB"];
buttonCell.Value = !(Boolean)checkCell.Value;
datagridSB.Invalidate();
}
else if (datagridSB.Columns[e.ColumnIndex].Name == "withProCSB")
{
DataGridViewCheckBoxCell buttonCell = (DataGridViewCheckBoxCell)datagridSB.Rows[e.RowIndex].Cells["withCashSB"];
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)datagridSB.Rows[e.RowIndex].Cells["withProCSB"];
buttonCell.Value = !(Boolean)checkCell.Value;
datagridSB.Invalidate();
}
}
private void datagridSB_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (datagridSB.IsCurrentCellDirty)
{
datagridSB.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
here is the answer to make two check boxes acts like two radio buttons ..

Enable/Disable the Save button correctly

Let's say we have a Win32 form with a Save toolbar button and some sontrols like a CheckBox are on the form, now we write a one line code for onchange event of checkbox to enable/disable the Save button. Let's say checkbox is selected at first, Save button disabled, now de-select the checkbox, Save button becomes enabled...now select the checkbox again Save button is still enabled...Same for a TextBox for example. Let's say its text is "Hi"...change it to "Hi Bye" , Save is enabled...change it BACK to "Hi" as it was, Save remains enabled...
Is there a model we can use to prevent these wrong enabling/disabling of save button?
You need to write some IF - ELSE code in the CheckedChanged event of the Checkbox. Check what is the current state by inspecting the Checked proeprty of the control (checkbox) ,If yes set the Enabled proeprty of the Button to true, else false.
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked)
button1.Enabled = true;
else
button1.Enabled = false;
}
Assuming checkBox2 is the name of the Checkbox and button1 is the name of the Save button.
You can use the same IF ELSE logic for other controls also. To Set the Value of the Textbox, Use the Text property
TextBox1.Text="I am gonna try something now"l
EDIT : As comecme suggested, If you only want to enable/disable button based on the checbox, It can be done in one line instead of the IF else block like this
button1.Enabled=checkBox2.Checked
You could store the last saved state, and compare the current state to it whenever it changes, to see if they're identical. If so, disable the button.
If these comparisons are expensive, you could make this more efficient, by calculating a hash value over all of the fields that need to be saved, and only doing the proper comparison if the hash of the last saved state matches the hash of the current state.
I prefer to put all my control state checking and setting into a single method:
private void UpdateControls()
{
saveButton.Enabled = checkBox1.Checked;
otherButton.Visible = checkBox2.Checked && textBox.Text.Length > 0;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
UpdateControls();
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
UpdateControls();
}
private void textBox_TextChanged(object sender, EventArgs e)
{
UpdateControls();
}
This means you just have one place in which to check and set the state, and makes it much easier to understand what is going on, especially when you have complex forms. I also prefer boolean expressions rather than if statements when assigning boolean variables, because it caters for both true and false without having to write a separate else statement (which may be forgotten).
I don't get where you're going with your checkbox, but I would use a Boolean variable:
private Boolean _canSave = false;
private Boolean CanSave
{
get { return _canSave; }
set
{
_canSave = value;
MenuSave.Enabled = value;
}
}
public void MenuSave_Click()
{
Save();
}
private void Save()
{
// do your thing
CanSave = false;
}
public void TextBox_TextChanged()
{
CanSave = true;
}
This won't account for disabling the saving menu when you revert the text back to its original. If you want that, you'll have to store the text in the Save() method in a private variable, and compare that to the current text on every TextBox_TextChanged() to determine whether a change compared to the original (i.e. since last save) has occurred.

WinForms ComboBox - How to Check Values

I am building a WinForms Application in C# .NET
The WinForms Application has a ComboBox where the DropDownStyle is set to DropDownList. When the App is launched, I read an XML file to populate the values of the ComboBox. And, at this time, nothing is selected in the ComboBox by default. As a result, buttons Change and Delete are disabled.
Now, when the user selects a value, I want the buttons Change and Delete to be enabled. So far I have accomplished (although, I am not sure that I have done it in the right way).
I have written the code in the SelectionChangeCommitted Event.
private void cbList_SelectionChangeCommitted(object sender, EventArgs e)
{
if (cbList.SelectedItem != null)
{
this.btnModify.Enabled = true;
this.btnRemove.Enabled = true;
}
else
{
this.btnModify.Enabled = false;
this.btnRemove.Enabled = false;
}
}
Now, when I chose a value...the buttons get enabled (as expected). The user then clicks on Delete button and we remove the selected value. Now, there is nothing Selected in the cbList but the buttons are still enabled?
What is the function/event where I check if a value is selected or not and then enable/disable the buttons.
At the moment, dont have Visual Studio, so I dont remember which events we have. But you can make this,
private void CheckButtons()
{
if (cbList.SelectedItem != null)
{
this.btnModify.Enabled = true;
this.btnRemove.Enabled = true;
}
else
{
this.btnModify.Enabled = false;
this.btnRemove.Enabled = false;
}
}
and use your func in event
private void cbList_SelectionChangeCommitted(object sender, EventArgs e)
{
CheckButtons();
}
as you said, after deleting, buttons are still visible, so you can put CheckButtons() function after your delete function like
DeleteX();
CheckButtons();

Cancel uncheck in WPF

I use checkbox in WPF window. I use some logic in unchecked event of checkbox. And I want to cancel uncheck if need it in the body of this event. How can I do this?
private void chApprove_Checked(object sender, RoutedEventArgs e)
{
btnAddDepartment.IsEnabled = true;
brnRemoveDepartment.IsEnabled = true;
}
private void chApprove_Unchecked(object sender, RoutedEventArgs e)
{
if (lbSource.Count == 0)
{
btnAddDepartment.IsEnabled = false;
brnRemoveDepartment.IsEnabled = false;
}
else
{
MessageBox.Show("Staff already in use! Release it first from dependecies!");
CheckBox myCheckBox = e.Source as CheckBox;
myCheckBox.IsChecked = true;
}
}
Impossible to cancel uncheck !!!
void CheckBox1_Unchecked(object sender, RoutedEventArgs e)
{
if(ResultOfSomeLogic)
{
CheckBox myCheckBox = e.Source as CheckBox;
myCheckBox.IsChecked = True; // Check it again
}
else
{
}
}
Also take a look at EventToCommand Binding Behaviour in MVVM Light to take advantage of CanExecute method.
You could do this easily with an attached behavior (rather than using code behind), you can take a look at this answer if you need a sample of how to structure one (it's only a few lines of code).
My spider-sense is telling me this isn't a very good idea though - I can't imagine a way to "justify" rechecking a checkbox that a user has clicked, it just strikes me as very jarring. Can you not either bind the enabled state of the checkbox to a property on your ViewModel or, if you have an ICommand bound to it, use the CanExecute delegate to enable/disable it based on the same logic?
Bind the IsChecked property of check box. Like
IsChecked="{Binding IsChecked, Mode = TwoWay}"
and in your class define some thing like dis;
private bool isChecked;
public bool IsChecked
{
get
{
return this.isChecked;
}
set
{
this.isChecked = value;
OnPropertyChanged["IsChecked"];
}
}
and in your event
void CheckBox1_Unchecked(object sender, RoutedEventArgs e)
{
if(ResultOfSomeLogic)
{
this.IsChecked = true;
}
else
{
}
}
hope this will work for u..
Good Luck..
In my case, I could not use a solution that allowed unchecking in the first place. If the checked state initiates a critical asynchronous operation, it is not always ideal to uncheck just to check it again: Why allow cancelling this operation if it shouldn't have been allowed to cancel in the first place?
For MenuItems, you can subscribe to the PreviewMouseDown event and set IsCheckable to false; then subscribe to the Click event and set IsCheckable back to true. The reason this works is because IsCheckable just determines whether or not to initiate the state change, unlike IsHitTestEnabled="false" and IsEnabled="False", which will stop all events from firing.
If you try to disable it, no subsequent events will fire making it impossible to restore checkability; by making it uncheckable beforehand, we avoid this mistake. Click also happens to occur after the state would've been changed so it works out quite nicely.
Unfortunately, CheckBox does not have an equivalent IsCheckable property; however, the same concepts described above (i.e., PreviewMouseDown, Click pattern) can produce a similar, if not identical, result.
Well assuming a check box is intended to interact with users instead of programmatic ways, there's a simple way to cancel Unchecked events based on some logic when user hits left mouse button or space bar:
private void CheckBox_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
// If it's already checked so next click would uncheck it hence trigger the Unchecked event.
if ((sender as System.Windows.Controls.CheckBox).IsChecked == true)
{
var isConfirmed = false; // Use your confirmation logic here instead.
// If e.Handled is set to false that will cancel further events such as the Unchecked event.
e.Handled = isConfirmed;
}
}
private void CheckBox_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
// If it's already checked so when user presses space bar it would uncheck it hence trigger the Unchecked event.
if ((sender as System.Windows.Controls.CheckBox).IsChecked == true)
{
if (e.Key == System.Windows.Input.Key.Space)
{
var isConfirmed = false; // Use your confirmation logic here instead.
// If e.Handled is set to false that will cancel further events such as the Unchecked event.
e.Handled = isConfirmed;
}
}
}

How to prevent/cancel a combobox's value change in c#?

I have a combobox at the top of a form that loads editable data into fields below. If the user has made changes, but not saved, and tries to select a different option from the combobox, I want to warn them and give them a chance to cancel or save.
I am in need of a "BeforeValueChange" event with a cancelable event argument.
Any advice on how to accomplish?
Save the ComboBox's SelectedIndex when to box if first entered, and then restore it's value when you need to cancel the change.
cbx_Example.Enter += cbx_Example_Enter;
cbx_Example.SelectionChangeCommitted += cbx_Example_SelectionChangeCommitted;
...
private int prevExampleIndex = 0;
private void cbx_Example_Enter(object sender, EventArgs e)
{
prevExampleIndex = cbx_Example.SelectedIndex;
}
private void cbx_Example_SelectionChangeCommitted(object sender, EventArgs e)
{
// some custom flag to determine Edit mode
if (mode == FormModes.EDIT)
{
cbx_Example.SelectedIndex = prevExampleIndex;
}
}
Here is the simplest fix:-
bool isSelectionHandled = true;
void CmbBx_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (isSelectionHandled)
{
MessageBoxResult result = MessageBox.Show("Do you wish to continue selection change?", this.Title, MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.No)
{
ComboBox combo = (ComboBox)sender;
isSelectionHandled = false;
if (e.RemovedItems.Count > 0)
combo.SelectedItem = e.RemovedItems[0];
return;
}
}
isSelectionHandled = true;
}
Save the current value on the Enter event.
Implement the BeforeValueChange logic in the ValueChanged event, before the actual ValueChanged logic. If the user cancels, set the stored value and don't continue in the method (return).
If you're going to use this system a lot, I'd suggest inheriting ComboBox and implementing your BeforeValuechange event there.
The Validating event can be used for this scenario
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating.aspx
You don't get an appropriate event by default. You could cache the previous value and set it back to that if the user wants to cancel.
How about using the Validating / Validated events?
It works well, if the event happening on LostFocus instead of Change is ok with you.
Otherwise, how about
public void Combobox_ValueChanged(object sender, EventArgs e) {
if (!AskUserIfHeIsSureHeWantsToChangeTheValue())
{
// Set previous value
return;
}
// perform rest of onChange code
}
You could use a message filter to intercept clicks and key presses, which would allow you to prevent the combo box's normal behaviour. But I think you'd be better off disabling the combo box when the user makes a change, and require them to either save or revert their changes.
You can't really prevent it, but you can change it back to the old value if certain requirements aren't met:
private SomeObject = selectedSomeObject=null;
private void cbxTemplates_SelectionChangeCommitted(object sender, EventArgs e)
{
if (!(sender is ComboBox cb)) return;
if (!(cb.SelectedItem is SomeObject tem)) return;
if (MessageBox.Show("You sure?", "??.",
MessageBoxButtons.OKCancel) != DialogResult.OK)
cb.SelectedItem = selectedSomeObject;
else
{
selectedSomeObject = tem;
}
}

Categories

Resources