Unchecking a Previously Selected Checkbox when another checkbox is checked - vb.net

My form has 3 checkboxes available to the User. When the User mistakenly checks one Checkbox and realizes the mistake then checks the correct Checkbox, I need the incorrect checked Checkbox to Uncheck automatically.
I have diligently searched the web but have been unable to find any sites that offer answers for VB 2010. Mostly they provide solutions for HTML, Excel, Java, etc.
Private Sub BeginnerForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
StartupForm.Close()
If Me.CheckBox1.Checked Then
Me.CheckBox2.Checked = False
Me.CheckBox3.Checked = False
ElseIf Me.CheckBox2.Checked Then
Me.CheckBox1.Checked = False
Me.CheckBox3.Checked = False
ElseIf Me.CheckBox3.Checked Then
Me.CheckBox1.Checked = False
Me.CheckBox2.Checked = False
End If
End Sub
The results of this code is that it does not uncheck the Checkbox(es). I get no error code, it just does not UNCHECK the Checkbox(es). I have also tried other code entries such as Me.Checkbox2.CheckState.Checked = CheckState.Unchecked to no avail. Trusting you can steer me in the right direction to UNCHECK a Checkbox when another Checkbox is CHECKED.

First of all, as mentioned by daShier, you place the code in the wrong event handler. Since you want to uncheck the other checkboxes when one is being checked, you must put the code in the either Click or CheckChanged event handler of all your checkboxes that take part in this selection logic. I would suggest to put in the CheckChanged event since it will be triggered even when your checkbox check state is changed through code in addition to through mouse or keyboard actions.
' declare variable to keep track of the previous selected checkbox
Dim prevSelectedCheckBox As CheckBox
' all checkboxes to be controlled are handled by this event handler
Private Sub CheckBoxes_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged, CheckBox2.CheckedChanged, CheckBox3.CheckedChanged
' first, identify which checkbox is triggering this event
Dim this As CheckBox = DirectCast(sender, CheckBox)
' if this event is triggered when this checkbox is being checked
If this.Checked Then
' if there is a checkbox previously selected/checked
If prevSelectedCheckBox IsNot Nothing Then
prevSelectedCheckBox.Checked = False ' uncheck it
End If
' now this checkbox is currently the checked one, save it to the variable
prevSelectedCheckBox = this
' if event is triggered by unchecking this checkbox, and this checkbox is the previously checked checkbox
ElseIf this.Equals(prevSelectedCheckBox) Then
' clear the variable since now, there is no checkbox is being checked
prevSelectedCheckBox = Nothing
End If
End Sub
However, if user can only select one option among the options represented by the checkboxes, you better use radio button instead.

It appears you are processing the code in the wrong handler. You are changing things when closing the form. Try moving the code to the CheckBoxx.CheckedChanged handlers:
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
CheckBox2.Checked = False
CheckBox3.Checked = False
End Sub
UPDATE: I realize that your original code that I copied and pasted would cause a loop since the changing of the checkbox states would trigger the other routines. It's not necessary since you only need clear the other boxes if the box your user is clicking is checked.
You will need to add similar code to CheckBox2.CheckedChanged and CheckBox3.CheckedChanged as well.
Also, I should point out that you are trying to make checkboxes act as radio buttons. Why not replace the checkbox controls with radio buttons instead so that VB handles the one-only behavior for you?

Related

Make listview with checkboxes act like checkbox list

I need a checkbox list that I can add read-only items (hence using a listview so I can gray-out an item and keep a user from selecting it).
However, when I click the item, the checkbox doesn't toggle. But when I add the following code to the item click event,
Private Sub LVSubFiles_Click(sender As Object, e As EventArgs) Handles LVSubFiles.Click
If LVSubFiles.Items(LVSubFiles.FocusedItem.Index).ForeColor <> Drawing.Color.Gray Then
If LVSubFiles.Items(LVSubFiles.FocusedItem.Index).Checked = True Then
LVSubFiles.Items(LVSubFiles.FocusedItem.Index).Checked = False
Else
LVSubFiles.Items(LVSubFiles.FocusedItem.Index).Checked = True
End If
End If
End Sub
But in this case when the user clicks on the checkbox rather than the item, nothing happens, as well selecting any other checkbox checks both the highlighted item and the checkbox of the new item selected.
Is there a way I can make the items act like a checkbox list? I've tried using Data Grid View, but i run into similar issues and a lot of code is based on the actions of this listview.
For those who find this question. I ultimately went with a hidden column which tracked "read only" items. Whenever the list would update the read-only tags would turn the item gray, but still enable it to be checked.
In regard to how the list interacted with the user, I moved the action items into the two categories and this seems to be working smoothly. The user can select/deselect with a single click regardless of which part of the item is clicked.
Private Sub dgvSubFiles_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvSubFiles.CellContentClick
If dgvSubFiles(dgvSubFiles.Columns("chkSubFiles").Index, dgvSubFiles.CurrentCell.RowIndex).Value = True Then
dgvSubFiles(dgvSubFiles.Columns("chkSubFiles").Index, dgvSubFiles.CurrentCell.RowIndex).Value = False
Else
dgvSubFiles(dgvSubFiles.Columns("chkSubFiles").Index, dgvSubFiles.CurrentCell.RowIndex).Value = True
End If
End Sub
Private Sub dgvSubFiles_SelectionChanged(sender As Object, e As EventArgs) Handles dgvSubFiles.SelectionChanged
dgvSubFiles.ClearSelection()
End Sub

Show ContextMenuStripItem without clicking off the current cell

I'm using an UltraGrid which has a ContextMenuStrip with 2 items. These are shown when right-clicking an UltraGridCell.
However, in order to show them, the user has to first click off the cell to take it out of edit mode, then right click on it to show the ContextMenuStripItems.
This has become confusing and irritating to the user, so I was wondering if there is any way that it can be changed to show them when right clicking whilst still in edit mode?
I've tried this to take it out of edit mode after a key is pressed, but it doesn't work.
Private Sub ugComm_keyup(sender As Object, e As KeyEventArgs) Handles ugComm.KeyUp
ugComm.UpdateData()
If ugComm.ActiveCell.IsInEditMode = True Then
ugComm.ActiveCell.Row.Update()
End If
End Sub
I also tried something in the MouseClick that was suggested on the Infragistics forums, but again it didn't work.
Is there any way that a user right-clicking a cell that is in edit mode can bring up the ContextMenuStripItems rather than this menu?
The above image shows what is currently show when right-clicking a cell in edit mode (The cell is the bottom right white cell). I don't want this to appear, but the CMS instead.
EDIT
I've tried the suggestions in the current answers, but neither of those worked for me. Possibly because the grids are a slightly older version?
My most recent effort was done with the following code:
Private Sub ugComm_MouseDown(sender As Object, e As MouseEventArgs) Handles ugComm.MouseDown
If e.Button = Windows.Forms.MouseButtons.Right Then
Me.cmCommRate.Show(mouseX, mouseY)
End If
End Sub
But this wasn't triggered until the cell was no longer in edit mode.
NEITHER OF THE ANSWERS BELOW RESOLVE THE ISSUE. STILL NEEDS AN ANSWER
When any cell of the grid enters in edit mode a TextBox is drawn over the cell. The nice part here is this text box is reused for all the cells in the grid. When you right click on the cell in edit mode the default context menu, that comes from MS, shows. What you need to do is get this text box and assign it your context menu strip. You can do this by handling ControlAdded event of the grid like this:
' create a field to store the TextBox
Private cellTextBox As TextBox
Private Sub grid_ControlAdded(sender As Object, e As ControlEventArgs) Handles grid.ControlAdded
' Check if added control is TextBox
If TypeOf e.Control Is TextBox Then
' If added control is TextBox store it in your private field and set its ContextMenuStrip
If Me.cellTextBox Is Nothing Then
Me.cellTextBox = DirectCast(e.Control, TextBox)
Me.cellTextBox.ContextMenuStrip = Me.ctx
End If
End If
End Sub
I have tried to write an event handler for the MouseUp event with this code
Private Sub grid_MouseUp(sender As Object, e as MouseEventArgs) Handles grid.KeyUp
grid.PerformAction(UltraGridAction.ExitEditMode)
grid.ContextMenuStrip.Show()
End Sub
and it works.
The ContextMenuStrip was added in code with this text (as example)
ContextMenuStrip ctx = new ContextMenuStrip()
ctx.Items.Add("Test1")
ctx.Items.Add("Test2")
ctx.Items.Add("Test3")
grid.ContextMenuStrip = ctx

Disable Button If Combox Input Deleted

In my project, I have a few textbox inputs, and some combo boxes with maybe 2 indexed items on a form. There's a button I'm disabling on load if no input is supplied to both textbox inputs, and it works great even if I delete out any text. However, I'm having issues with forcing the combo box to behave in the same manner. This work however:
Private Sub cboPickShirts_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboPickShirts.SelectedIndexChanged
InputCheck_3 = True
If cboPickShirts.SelectedIndex < 0 Then
InputCheck_3 = False
End If
If InputCheck_3 = False Then
btnInputResult.Enabled = False
ElseIf InputCheck_3 = True Then
btnInputResult.Enabled = True
End If
End Sub
I have InputCheck_3 set up as a global variable in a Public Module. On form load, I'm disabling my button and it doesn't enable until I select one of the indexed items. My struggle to get the button disable again if any combo box text is entered and deleted out, leaving it null or empty. Any thoughts on what I'm missing or what I can add to get results? I guess I need a variable or event to notice the change (entering & deletion of text).
The problem you are having is that your SelectedIndexChanged event is not being triggered when you remove the selected item from your ComboBox. I would use the TextChanged event of your TextBox's and ComboBox and give it a common handler and check it that way. Something like this
Private Sub TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged, cboPickShirts.TextChanged
EnableCheck()
End Sub
Private Sub EnableCheck()
btnInputResult.Enabled = (String.IsNullOrEmpty(TextBox1.Text) And String.IsNullOrEmpty(TextBox2.Text) And ComboBox1.SelectedIndex = -1)
End Sub
You can also check that the comboBox is NullorEmpty the same way as the textbox's. As it stands right now the combobox will be enabled when the text no longer matches a selection.
One line code
btnInputResult.Enabled = If((cboPickShirts.SelectedIndex<0),False, True)

Unselect/deselect row in DataGridView on click

I'm in the process of migrating VB6 code to VB.NET and we're up to the VS2013 stage, using .NET 4.5.2. In the original code, there are FlexGrids that allow row deletion on double-click and row selection/deselection on single click. I've got double-click going fine, it deletes the row and sets all rows as deselected (because double-clicking the header cell was re-ordering the rows and selecting a row, without a click on the row, and then deleting the now selected row). I don't know if that's relevant, but I've included it just in case.
I've looked here but it doesn't help because this behavior is expected and I don't know if the client will want to hear that everyone has to be re-trained to use the CTRL+click method to deselect. If that's how it must be, then so be it, but I have to try to make this work.
Using the cell click event to do something like this
Private Sub grdSelectedOps_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles grdSelectedOps.CellClick
If Not grdSelectedOps(e.ColumnIndex, e.RowIndex).Selected Then
grdSelectedOps(grdSelectedOps.CurrentCell.ColumnIndex, grdSelectedOps.CurrentCell.RowIndex).Selected = True
Else
grdSelectedOps(grdSelectedOps.CurrentCell.ColumnIndex, grdSelectedOps.CurrentCell.RowIndex).Selected = False
End If
End Sub
doesn't work, because if you've clicked the cell you've selected it, so it always immediately deselects it. Multi-select is off. Is this possible?
Your Question is answered Here:
Toggle Selection in DataGrid
It is C# so here is the equivalent VB.NET Code is:
REM Keeps track of selection status
Private selectionChanged As Boolean
REM Fires Second
Private Sub dataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs)
If Not selectionChanged Then
dataGridView1.ClearSelection()
selectionChanged = True
Else
selectionChanged = False
End If
End Sub
REm Fires first
Private Sub dataGridView1_SelectionChanged(sender As Object, e As EventArgs)
selectionChanged = True
End Sub
You may want to override the DataGrid Control to provide this functionality internally, but that is up to you.

Checkbox events when Form is opened and closed fire when form is reloaded

First... I am open to skinning this cat a different way if I am going at it wrong to begin with. Using VB 2010 .net 4.0 and I am very much a beginner.
I am making a product billing application that has a main form and a subform with additional options. Whenever that subform is reopened after being opened once, the checkbox events that were selected are blank by default. If I recheck them (so someone can uncheck) then any that are rechecked all refire and increase the variable again.
I ultimately need to be able to open that second form after closing it, display any checkboxes that were selected before as selected again and not increase the variable in the process.
Main form Checkbox code to set booleans and increase or decrease subtotal variable of most used products.
Private Sub chkbox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkbox1.CheckedChanged
If chkbox1.Checked = True Then
bChkbox1 = True
Subtotal += 15
Else
bChkbox1 = False
Subtotal -= 15
End If
End Sub
Main form button to launch subform with all products listed.
Private Sub btnAllProducts_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAllProducts.Click
Form3.Show()
End Sub
Subform checkbox code works perfectly the first time it is opened but not when relaunched.
Private Sub chkbox2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkbox2.CheckedChanged
If chkbox2.Checked = True Then 'also tried without the nested if with same results
If Me.IsHandleCreated = True Then 'me.visible behaves the same way
MsgBox("form visible true")'launches after clicking button but before form is actually on screen
Form1.bcheckbox2 = True
Form1.Subtotal += 105
End If
Else
Form1.bcheckbox2 = False
Form1.Subtotal -= 105
End If
End Sub
Booleans are used to check boxes that were checked on the main page or when it was open before.
If Form1.bcheckbox2 = True Then
chkbox2.Checked = True
End If
As I said, I can completely rework the code if it makes sense to do so or just fix something if I have made some sort of mistake.
For example, I was thinking of changing to wipe the subtotal on each form load and rebuild it based off the toggled booleans but it seems like there should be a much more elegant way with less overhead and I am just doing something incorrectly.
It is not common to have to tell checks and radios to ignore events while loading the form. You just need an Ignore or Loaded flag:
Public Class Form1
Private ignore As Boolean = True
...
Private Sub Form1_Load(...
' do normal stuff
ignore = False ' should be the ONLY place it is set
End Sub
Private Sub CheckBox2_CheckedChanged(...
If ignore Then Exit Sub
End Sub
The Form Designer code will fire events as it creates the form and controls, which CAN be handy for initializing stuff but often it causes trouble. Some controls will even get the same event twice. There isnt really a "reload" action for forms. If you hide them, Show() won't fire the Load event again.
You can avoid the flag and manually add the handlers for the troublesome controls when the form loads, but that can be tedious if there are lots of them. Flags can be abused and misused, but if it is set in that one spot only, its fine.
If someone is looking for alternative or have similar problem here's my workaround to detect event change so checkbox wouldn't get triggered on re-load:
If ((Me.CheckBox2.Value <> Sheets(1).Range("t6").Value) And (Me.CheckBox2 = True)) = True Then
' do your stuff
Me.CheckBox2.Value = False
Else
Me.CheckBox2.Value = True
End If
Where Sheets(1).Range("t6").Value is where checkbox2 value is being stored.
I have this assigned to a msgbox input so when vbno event is being triggered else is executed.
Cheers.