How to disable the accept button in code - vb.net

In Microsoft Visual Basic 2010, a form has a property called AcceptButton. This can be set to the ok button of the form in the designer or by code, like this Me.AcceptButton = Me.OKbutton.
I would like to know how to disable this property in code, with something like Me.AcceptButton = Null, note this does not work. In the designer this property can be left set to (none).
The reason I would like to know how to achieve this is as follows. I have a textbox that the user enters data into; when they press enter an error check is done. This uses the following code
Private Sub textbox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles textbox1.KeyDown
If e.KeyCode = Keys.Return Then
The problem I am having is that this code does not run if the AcceptButton property is enabled, due to the dual use of the return key. I would therefore like to temporarily disable then re-enable the AcceptButton property using code.
If I do not set the AcceptButton this code will run.

Don't tinker with the AcceptButton property, it gives important feedback to the user. Fix the real problem, set the TextBox' AcceptsReturn property to True.

If you still want to disable accept button use as Me.AcceptButton = Nothing

Leave the AcceptButton() property not set. Then, in your KeyDown() handler, if enter is pressed and everything passes your tests:
OKbutton.PerformClick()

Another approach is to disable your button and then only re-enable it when your conditions are met. Then you don't have to trap Enter in the TextBox handler. Here's a simply example:
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.AcceptButton = Me.OKbutton
Me.OKbutton.Enabled = False
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As System.EventArgs) Handles TextBox1.TextChanged
ValidateEntries()
End Sub
Private Sub ValidateEntries()
' ... put your logic in here to determine if all the fields in the form are in a valid state ...
' set the Enabled state of OKbutton accordingly:
Dim valid As Boolean = True ' assume valid until proven otherwise
' Made up validation code:
Dim value As Integer
If Integer.TryParse(TextBox1.Text, value) Then
If value < 60 Then
valid = False
End If
Else
valid = False
End If
Me.OKbutton.Enabled = valid
End Sub
Private Sub OKbutton_Click(sender As Object, e As System.EventArgs) Handles OKbutton.Click
MessageBox.Show("OK")
End Sub
End Class

Related

Changed checked state on checkbox with button appearance in VB.NET

As stated in my summary, I am currently working on a Virtual OS in VB.Net. I am currently working on the session as I am done with the login stuff.
I am having trouble with a checkbox with button appearance. I want to set the CheckState to Checked if I click on the button with the Click() event like this:
Private Sub btnApps_Click(Byval sender As Object, Byval e As EventArgs) Handles btnApps.Click()
If btnApps.CheckState = CheckState.Checked Then
btnApps.CheckState = CheckState.Unchecked
Else
btnApps.CheckState = CheckState.Checked
End If
End Sub
I also tried the Checked property.
This code is not working at all, if I put the whole If-End If section in the CheckedChanged event I get a StackOverflowException. What am I doing wrong?
The CheckBox is a custom control b.t.w.
If you'd like to prevent your Checkbox from automatically changing state and change the appearance with your own Click event, you can turn AutoCheck to false.
https://msdn.microsoft.com/en-us/library/system.windows.forms.checkbox.autocheck(v=vs.110).aspx
Information found thanks to this question: How to cancel RadioButton or CheckBox checked change
Public Class Form1
Private WithEvents btnApps As New clsChk
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
btnApps.AutoCheck = False
Me.Controls.Add(btnApps)
End Sub
Private Sub btnApps_Click(sender As Object, e As EventArgs) Handles btnApps.Click
Debug.WriteLine(btnApps.CheckState)
If btnApps.CheckState = CheckState.Checked Then
btnApps.CheckState = CheckState.Unchecked
Else
btnApps.CheckState = CheckState.Checked
End If
End Sub
End Class

Call a control event handler with multiple controls

Private Sub NullValidation(sender As Object, e As EventArgs) Handles FirstNameTextBox.Validating,
LastNameTextBox.Validating, FatherNameTextBox.Validating,
If String.IsNullOrWhiteSpace(sender.Text) Then
ErrorProvider1.SetError(sender, "Text box is empty ")
End If
End Sub
I want to check my controls validation out of this event handler (in a button click handler). But as it requires sender and e arguments it won't works. How can I do it?
Because number of controls are more than what I have wrote here(more than just FirstNameTextBox and LastNameTextBox), it doesn't seem a good solution to write a validation code for every one of them. But as it requires sender and e arguments it won't works. How can I do it?
First thing you should do is to set option strict on. You're not using the correct method signature. The validating event is defined as:
Public Delegate Sub CancelEventHandler(ByVal sender As Object, ByVal e As CancelEventArgs)
Change the type of e from EventArgs to CancelEventArgs. You may need to import the namespace System.ComponentModel. Then set e.Cancel to True to indicate that the validation didn't pass.
Private Sub NullValidation(sender As Object, e As CancelEventArgs) Handles FirstNameTextBox.Validating, LastNameTextBox.Validating, FatherNameTextBox.Validating
Dim ctl As Control = TryCast(sender, Control)
If ((Not ctl Is Nothing) AndAlso String.IsNullOrWhiteSpace(ctl.Text)) Then
e.Cancel = True
Me.ErrorProvider1.SetError(ctl, "Text box is empty ")
End If
End Sub

Setting focus to a textbox control

If I want to set the focus on a textbox when the form is first opened, then at design time, I can set it's tabOrder property to 0 and make sure no other form control has a tabOrder of 0.
If I want to achieve the same result at run-time, using code, how should I proceed?
Are there alternatives to using tabOrder?
I assume any run-time code will be in the form's constructor or its onload event handler?
EDIT
In other words I'd like to be able to type straight into the textbox as soon as the form appears without having to manually tab to it, or manually select it.
Because you want to set it when the form loads, you have to first .Show() the form before you can call the .Focus() method. The form cannot take focus in the Load event until you show the form
Private Sub RibbonForm1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Show()
TextBox1.Select()
End Sub
I think what you're looking for is:
textBox1.Select();
in the constructor. (This is in C#. Maybe in VB that would be the same but without the semicolon.)
From http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx :
Focus is a low-level method intended primarily for custom control
authors. Instead, application programmers should use the Select method
or the ActiveControl property for child controls, or the Activate
method for forms.
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
TextBox1.Select()
End Sub
Using Focus method
Private Sub frmTest_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
yourControl.Focus()
End Sub
To set focus,
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
TextBox1.Focus()
End Sub
Set the TabIndex by
Me.TextBox1.TabIndex = 0
Quite simple :
For the tab control, you need to handle the _SelectedIndexChanged event:
Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As System.EventArgs) _
Handles TabControl1.SelectedIndexChanged
If TabControl1.SelectedTab.Name = "TabPage1" Then
TextBox2.Focus()
End If
If TabControl1.SelectedTab.Name = "TabPage2" Then
TextBox4.Focus()
End If
I think the appropriate event handler to use is "Shown".
And you only need to focus the appropriate text box.
Private Sub Me_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
myTextbox.Focus()
End Sub
create a textbox:
<TextBox Name="tb">
..hello..
</TextBox>
focus() ---> it is used to set input focus to the textbox control
tb.focus()

Select case with VB GUI (For School)

Greetings and salutations. I really need help for school.
This is what I'm dealing with:
Cannot make selection until one option is picked.
The "You have selected a hostel location" text shouldn't show up until "Select Location" is pressed.
My assignment is a hostel selection, allowing the user to select one or the other. Once the selection is made via btnselect, lblselected is supposed to show up, then the window is supposed to close.
Please help me. I have no idea what I'm doing. I'm a web designer trying to expand my knowledge.
Option Explicit On
Public Class frmhostelselection
Private Sub btnlondon_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlondon.Click
End Sub
Private Sub btndublin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndublin.Click
End Sub
Private Sub btnselect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnselect.Click
End Sub
Private Sub btnexit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnexit.Click
End Sub
Private Sub lblselected_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lblselected.Click
End Sub
Private Sub lblmsg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lblmsg.Click
End Sub
End Class
Ok, i get you a logic
First on you loadsub
you must add
londonlistbox.enabled = false
dublinlistbox.enabled = false
then, add to you london button
dublinlistbox.enabled = false
london.enabled = false
and add the opposite to the dublin button
then, select location
select case londonlistbox and dublinlistbox
case londonlistbox.enabled = true
label1.text = londonlistbox.selecteditems
case dublinlistbox.enabled = true
label1.text = dublinlistbox.selecteditems
that's all
You want to hide the label. In visual studio, you want to select the label, and set its visible value to false. Or you can set it to be invisible for the formload event.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lblselected.visible = false
end sub
You then need it to show for the button click event.
lblselected.visible = true
From your picture i am unsure what the buttons are to do. You seem to have 2 actual locations to choose (as buttons) and another button which seems to act as a select button.
You also have requested a select case command in your question.
So perhaps you want t select case to load when you click the select location button, and that a value will be set if you click either of the other buttons?
As above said, you have made no attempt to try this yourself, so i won't write the code, but it sounds like you want this...
The 2nd label should be invisible until the select button is clicked.
You want to string or something that will identify what has been pressed. This string should be a global variable that is declared beneath the public path.
When either londen button or... other button is pressed, the global string should change to either London or...Dublin.
When you press the select button, it should load a select case method which will check for either london or dublin.
Select case globalstring
case "London"
' make label visible, maybe change lblselected text to reflect that London was pressed.
case "Dublin"
' Make label visible, maybe change lblselected text to reflect that Dublin was pressed.
case default
' Produce an error message saying that nothing was pressed.
end Select
I'm guessing you also want images to show in those pictureboxs. Use initial image to get that one.
And the exit button will just be me.close()

ComboBox's SelectedIndexChanged event not being called on Enter

I'm working on VS 2010 with VB using .NET Framework 4.0
I have a combobox. It has some items in it and displays just fine. Here's where it gets a little weird:
If I click the drop-down arrow on the combobox and CLICK on the item I want, SelectedIndexChanged is called - good.
If I click inside the text area of the combobox and start typing what I want selected and finish it by pressing the up (or down) key, SelectedIndexChanged is called - also good.
If I click the drop-down arrow on the combobox and start typing what I want selected and finish it by pressing ENTER, SelectedIndexChanged is not called - PROBLEM.
Is there a different event that is caused by the ENTER in the last case? I've tried using the TextChanged and TextUpdate events, but those do not seem to be working:
Private Sub cmbStatus_TextChanged(sender As System.Object, e As System.EventArgs) Handles cmbStatus.TextChanged
If e.Equals(Keys.Enter) Then
Call SomeMethod()
End If
Should I use something besides e.Equals(Keys.Enter)?
Is there another event I should be looking for?
EDIT:
An example of the items in the ComboBox are:
10 - NEW ENTRY AND COMPLETENESS CHECK ---> this is the most common type
13 - ASSIGNED TO TRB/HRB ---> there are a few with '/'
60 - EXTERNAL (HOLD UNTIL FURTHER NOTICE) ---> there are a few with '(' and ')'
Basically, the type of each listing is "## - SOME TEXT".
Disclaimer: this is written in C# - let me know if you need it translated to VB.
private void comboBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
//It's important to also check that the Combo Box is displaying its Drop Down. If
//you want this to execute even when it is not displayed, remove the check for
//comboBox1.DroppedDown.
if (e.KeyCode == Keys.Enter && comboBox1.DroppedDown &&
!string.IsNullOrEmpty(comboBox1.Text))
{
int index;
//Attempt to locate the string typed in by the user. An index of -1
//means it was not found.
if ((index = comboBox1.FindStringExact(comboBox1.Text)) != -1)
{
//Update the SelectedIndex.
comboBox1.SelectedIndex = index;
}
}
}
Interestingly, the docs say that we should be using the SelectionChangeCommitted event instead of the SelectedIndexChanged event when handling selection changes made by the user. It is necessary to do so in this case as the SelectedIndexChanged event fires twice using my approach.
Edit:
To prevent the user from having to type the entire string, use the advice from Adi's answer: go to the properties of the combo box and set set AutoCompleteMode to SuggestAppend and AutoCompleteSource to ListItems - I actully used these settings when creating my answer, so it should work for you.
Option Strict On
Public Class Form1
Friend WithEvents ComboBox1 As New ComboBox With {.Parent = Me}
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
ComboBox1.Items.AddRange({"hello", "tes1ted", "word", "item", "tes2ted"})
ComboBox1.Text = ComboBox1.Items(0).ToString
End Sub
Private Sub ComboBox1_KeyUp(ByVal sender As Object, ByVal e As KeyEventArgs) Handles ComboBox1.KeyUp
'You can put this in the keydown event, or adapt it a small bit and put it in the keypress event
'putting it in the textchanged event is problematic and not recommended.
Dim OriginalText As String = ComboBox1.Text
If e.KeyCode = Keys.Enter Then
If ComboBox1.SelectionLength > 0 Then
ComboBox1.Text = ComboBox1.Text
ComboBox1.SelectionLength = 0
ComboBox1.SelectionStart = ComboBox1.Text.Length
End If
End If
If Not IsTextKey(e.KeyCode) Then Exit Sub
Dim Filter As String = ComboBox1.Text & "*"
If Filter.Length = 1 Then Exit Sub
For I = 0 To ComboBox1.Items.Count - 1
If LCase(ComboBox1.Items(I).ToString) Like LCase(Filter) Then
ComboBox1.SelectedItem = ComboBox1.Items(I)
ComboBox1.Select(OriginalText.Length, (ComboBox1.Text.Length - OriginalText.Length))
Exit Sub
End If
Next
End Sub
Function IsTextKey(ByVal Key As Integer) As Boolean
Select Case True
Case Key = Keys.Up : Return False
Case Key = Keys.Down : Return False
Case Key = Keys.Left : Return False
Case Key = Keys.Right : Return False
Case Key = Keys.Back : Return False
Case Key = Keys.Delete : Return False
Case Key = Keys.LWin : Return False
Case Key = Keys.RWin : Return False
'add whatever I missed
'return false if the key either removes text from the textbox
'or does not produce a character
Case Else
'return true if the key produces a visible character(including space)
Return True
End Select
End Function
End Class
Private Sub ComboBox1_KeyUp(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles ComboBox1.KeyUp
If e.KeyCode = Keys.Enter Then
MessageBox.Show(ComboBox1.SelectedText)
Call SomeMethod()
End If
End Sub
I believe that you should set AutoCompleteMode to SuggestAppend and AutoCompleteSource to ListItems. This way, if what you type in is sustainable with the items loaded in the ComboBox, by writing it down and finding that item, when pressed Enter, the SelectedIndexChanged will be fired (even if a match wouldn't be found - the first in the list will be selected)
I've prepared something to point out this to you.
Regards,
Adi Konstantin
Subscribe to the KeyPressed event:
Private Sub yourComboBox_KeyPressed(sender As System.Object, e As System.KeyPressedEventArgs) Handles yourComboBox.KeyPressed
If e.KeyChar.Equals((char)Keys.Enter) Then
Call SomeMethod()
End If
this will helps your problems
Private Sub ComboBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles ComboBox1.KeyDown
If e.KeyCode = Keys.Enter Then
MsgBox("hello")'call some functions
End If
End Sub
Can you let me know if this works for you?
Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
If e.KeyChar = Chr(13) Then
ComboBox1_SelectedIndexChanged(sender, e)
End If
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
MsgBox(ComboBox1.Text)
'Your code here
End Sub
I had a similar problem when the combobox dropdownstyle was set to simple with autocomplete set to append, sourcing from my listitems. My workaround was to have a string variable save the combobox text upon each textchanged event. That way, when ENTER is pressed, you can retrieve the deleted text and reassign it to the combobox text.
'Global declaration
'Global declaraion
dim selected_text as string = ""
Private Sub combobox_textchanged(sender As Object, e As EventArgs) Handles combobox.TextChanged
If combobox.Text IsNot Nothing And combobox.Text <> "" Then
selected_text = combobox.Text
End If
End Sub
Private Sub combobox_keydown(sender As Object, e As KeyEventArgs) Handles combobox.KeyDown
If e.KeyCode = Keys.Enter Then
combobox.Text = selected_text
'put logic here
End If
End Sub
There are some great answers above, but I liked that I didn't need to sort out all the command keys and arrows etc.
Close the list manualy on PreviewKeyDown event:
Private Sub cmbStatus_PreviewKeyDown(sender As ComboBox, e As PreviewKeyDownEventArgs) Handles cmbStatus.PreviewKeyDown
If e.KeyCode = Keys.Enter Then sender.DroppedDown = False
End Sub