Clearing NumericUpDown - vb.net

My problem with NumericUpDown control is when the user selects a value from NumericUpDown And unchecks the checkBox1 and clicks the Save button, the value of NumericUpDown not cleared:
Public Class FormAdd
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.StudenttableBindingSource.AddNew()
End Sub
Private Sub BttnSave_Click(sender As Object, e As EventArgs) Handles BttnSave.Click
Me.StudenttableBindingSource.EndEdit()
Me.StudenttableTableAdapter.Update(Me.StudentDataSet.studenttable)
Me.StudenttableTableAdapter.Fill(Me.StudentDataSet.studenttable)
MsgBox(" Student Saveed", MsgBoxStyle.Information)
Me.StudenttableTableAdapter.Fill(Main.StudentDataSet.studenttable)
Me.Close()
End Sub
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked = False Then
AgeNumericUpDown.Value = AgeNumericUpDown.Minimum
AgeNumericUpDown.Text = ""
End If
End Sub
I need if the user selects a value and unchecks the CheckBox1 value of AgeNumericUpDown to reset to an empty string.
Illustrated:

Access the text control of the NumericUpDown and then set text to be blank
Private Sub CheckBox1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked = False Then
AgeNumericUpDown.Controls.Item(1).Text = ""
End If
End Sub

NumericUpDown does not contain string. It has value as numbers. So it should be:
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked = False Then
AgeNumericUpDown.Value = 0
End If
End Sub
EDIT:
Check this out then if you don't want the value to be zero, but empty!
Private Sub BttnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BttnSave.Click
If AgeNumericUpDown.Value <> 0 Then
AgeNumericUpDown.Controls(1).Text = ""
End If
End Sub

I was using the NumericUpDown control without the spinners because I wanted only numbers. The control was in a child dialog that was invoked from a listview selection. When the value to be loaded into the NumericUpDown control was zero in the listwiew, a zero was in the control. That zero always had to be cleared out. Here's how I made it "appear" blank. If it was zero, I change the ForeColor of the control to white. I added an Enter event that changed the ForeColor to black and deleted the zero.
This hid the NumericUpDown control spinners.
AccessCode.Controls[0].Visible = false;
These statements were in the form initialization. (var code was to be loaded into AccessCode)
if (code == 0)
{
AccessCode.ForeColor = Color.White;
}
The Enter event code looked like this.
private void AccessCode_Enter(object sender, EventArgs e)
{
if (AccessCode.ForeColor == Color.White)
{
AccessCode.ForeColor = Color.Black;
AccessCode.Focus();
SendKeys.SendWait("{Delete}");
}
}
The AccessCode control also had a Leave event that checked for valid data.

Related

Autocomplete text box. Selecting a value

good day!
there is a textbox autocomplete code
Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim day_source As New AutoCompleteStringCollection()
day_source.AddRange(System.Enum.GetNames(GetType(DayOfWeek)))
PrepareTextBox(TextBox1, day_source, AutoCompleteMode.SuggestAppend)
End Sub
Private Sub PrepareTextBox(ByVal txt As TextBox, ByVal source As AutoCompleteStringCollection, ByVal mode As AutoCompleteMode)
txt.AutoCompleteSource = AutoCompleteSource.CustomSource
txt.AutoCompleteCustomSource = source
txt.AutoCompleteMode = mode
End Sub
Tell me how you can display a message with the name of the selected value when you select a value?
The KeyDown event fires with e.KeyCode = 13 when the user presses Enter or Double Clicks on an item in the list.
Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyCode = 13 Then
MsgBox(TextBox1.Text)
End If
End Sub

cmbComboBox.SelectionStart always returns zero irrespective of cursor location

For some reason the "SelectionStart" property behaves differently from TextBox to ComboBox.
Create a TextBox and a ComboBox. Make sure DropDownStyle = DropDown (NOT DropDownList!)
Add these Leave events (same result if you use LostFocus event):
Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave
Debug.Print("Textbox: " & TextBox1.SelectionStart)
End Sub
Private Sub ComboBox1_Leave(sender As Object, e As EventArgs) Handles ComboBox1.Leave
Debug.Print("ComboBox: " & ComboBox1.SelectionStart)
End Sub
Now type text into each control and change focus from control to control, with the selection cursor in different places in the string.
I get this:
Textbox: 6
ComboBox: 0
Textbox: 8
ComboBox: 0
Textbox: 5
ComboBox: 0
Textbox: 4
ComboBox: 0
... and so on
When the textbox loses focus, it returns the correct SelectionStart.
When the combobox loses focus, it always returns zero.
Is there a reason, solution or reasonable workaround? I cannot seem to intercept this without creating a new variable for each combo control, and storing the SelectionStart on every click and keypress event (assuming the user might click the mouse, use arrow keys or type characters).
I just did some testing and it appears that the selection is reset between the Leave and LostFocus events as well as between the Enter and GotFocus events. I tried remembering the values on the first of each pair and restoring it on the second and it worked as desired:
Private comboBox1SelectionStart As Integer
Private comboBox1SelectionLength As Integer
Private Sub ComboBox1_Enter(sender As Object, e As EventArgs) Handles ComboBox1.Enter
comboBox1SelectionStart = ComboBox1.SelectionStart
comboBox1SelectionLength = ComboBox1.SelectionLength
End Sub
Private Sub ComboBox1_Leave(sender As Object, e As EventArgs) Handles ComboBox1.Leave
comboBox1SelectionStart = ComboBox1.SelectionStart
comboBox1SelectionLength = ComboBox1.SelectionLength
End Sub
Private Sub ComboBox1_GotFocus(sender As Object, e As EventArgs) Handles ComboBox1.GotFocus
ComboBox1.SelectionStart = comboBox1SelectionStart
ComboBox1.SelectionLength = comboBox1SelectionLength
End Sub
Private Sub ComboBox1_LostFocus(sender As Object, e As EventArgs) Handles ComboBox1.LostFocus
ComboBox1.SelectionStart = comboBox1SelectionStart
ComboBox1.SelectionLength = comboBox1SelectionLength
End Sub
You don't want to have to do that every time for every CokmboBox so you can build it into a custom control and then use that in place of the standard control:
Public Class ComboBoxEx
Inherits ComboBox
Private selectionStartTemp As Integer
Private selectionLengthTemp As Integer
Protected Overrides Sub OnEnter(e As EventArgs)
MyBase.OnEnter(e)
'Remember the current selection.
selectionStartTemp = SelectionStart
selectionLengthTemp = SelectionLength
End Sub
Protected Overrides Sub OnGotFocus(e As EventArgs)
'Restore the selection.
SelectionStart = selectionStartTemp
SelectionLength = selectionLengthTemp
MyBase.OnGotFocus(e)
End Sub
Protected Overrides Sub OnLeave(e As EventArgs)
MyBase.OnLeave(e)
'Remember the current selection.
selectionStartTemp = SelectionStart
selectionLengthTemp = SelectionLength
End Sub
Protected Overrides Sub OnLostFocus(e As EventArgs)
'Restore the selection.
SelectionStart = selectionStartTemp
SelectionLength = selectionLengthTemp
MyBase.OnLostFocus(e)
End Sub
End Class
A side-effect of this is that you will see the text selected even when the control doesn't have focus. The ComboBox has no HideSelection property like the TextBox does. If you don't like this then I'd imagine that you could find a way to make it behave like the TextBox does but that's a different question so I won't go into it here.
I think I've got it, using your idea but just setting the value in a different location.
Dim ComboSelectionStart As Integer
Private Sub cmbComboBox_KeyUp(sender As Object, e As KeyEventArgs) Handles cmbComboBox.KeyUp
'Store selection on any key press
ComboSelectionStart = cmbComboBox.SelectionStart
End Sub
Private Sub cmbComboBox_MouseClick(sender As Object, e As MouseEventArgs) Handles cmbComboBox.MouseClick
'Store selection on any mouse click
ComboSelectionStart = cmbComboBox.SelectionStart
End Sub
Private Sub cmbComboBox_Leave(sender As Object, e As EventArgs) Handles cmbComboBox.Leave
'Returns correct value here because it was not altered by LostFocus event
Debug.Print(ComboSelectionStart .ToString)
End Sub
When you modify the OnLeave() sub in the class provided by #jmcilhinney it actually works nicely.
Protected Overrides Sub OnLeave(e As EventArgs)
'Remember the current selection.
selectionStartTemp = SelectionStart
selectionLengthTemp = SelectionLength
MyBase.OnLeave(e) 'this has to go last because it modifies the SelectionStart...
End Sub

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

Making combobox visible when it is disabled

I am disabling combobox in VB.net.
But in disable mode it not visible properly.
I tried changing both BackColor and ForeColor but it is not working.
Code :
cmbbox.BackColor = Color.FromName("Window")
or
cmbbox.ForeColor = Color.FromName("Window")
Please help
Dear Adam:
I am making my component enable false.But I want to make it viewable.You can reffer the link.This is what exacly I want but in VB.Net : A combobox that looks decent when it is disabled
To achieve disabling combobox without fading it, first change the dropdown style of the combobox to DropDownList, Then tweak with the events to achieve the goal.
Here is a piece of code by which you can achieve the same:
Public Class Form1
Dim selectindex As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.Items.Add("1")
ComboBox1.Items.Add("2")
ComboBox1.Items.Add("3")
ComboBox1.Items.Add("4")
selectindex = 3
ComboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
ComboBox1.SelectedIndex = selectindex
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectionChangeCommitted
ComboBox1.SelectedIndex = selectindex
End Sub
End Class
Create anew form Form1 and add a combobox to the form, then add the above code to get a readonly combobox.
Have a look at this thread which has a solution for a readonly combobox and the code is all VB.NET.
A version of their code is as follows. You'll need to but it inside a class of your own which inherits System.Windows.Forms.ComboBox
Private _ReadOnly As Boolean = False
Public Property [ReadOnly]() As Boolean
Get
Return _ReadOnly
End Get
Set(ByVal Value As Boolean)
_ReadOnly = Value
End Set
End Property
Public Overrides Function PreProcessMessage(ByRef msg As Message) As Boolean
'Prevent keyboard entry if control is ReadOnly
If _ReadOnly = True Then
'Check if its a keydown message
If msg.Msg = &H100 Then
'Get the key that was pressed
Dim key As Int32 = msg.WParam.ToInt32
'Ignore navigation keys
If key = Keys.Tab Or key = Keys.Left Or key = Keys.Right Then
'Do nothing
Else
Return True
End If
End If
End If
'Call base method so delegates receive event
Return MyBase.PreProcessMessage(msg)
End Function
Protected Overrides Sub WndProc(ByRef m As Message)
'Prevent list displaying if ReadOnly
If _ReadOnly = True Then
If m.Msg = &H201 OrElse m.Msg = &H203 Then
Return
End If
End If
'Call base method so delegates receive event
MyBase.WndProc(m)
End Sub
I've been looking for the same not long ago and ended up doing the following. You may not like it, but i'll share it in case. I am using TableLayoutPanel to arrange my controls on the form and then i am swapping the positions of the desired controls.
For example I've created the following Items:
Form1 Design
TableLayoutPanel1 (two columns, three rows)
TextBox1 Read-only = True, BackColor = White
ComboBox1 Visible = False, DropDownStyle = DropDownList, FlatStyle = Popup
Button1 (named it to Change)
Button2 (named it to Done) -> Visible = False
Runtime - Screenshots
Here is my code:
Public Class Form1
Private Sub SwapControls(tlp As TableLayoutPanel, ctr1 As Control, ctr2 As Control)
Dim ctl1pos As TableLayoutPanelCellPosition = tlp.GetPositionFromControl(ctr1)
ctr1.Visible = False
tlp.SetCellPosition(ctr1, tlp.GetPositionFromControl(ctr2))
ctr2.Visible = True
tlp.SetCellPosition(ctr2, ctl1pos)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SwapControls(TableLayoutPanel1, TextBox1, ComboBox1)
SwapControls(TableLayoutPanel1, Button1, Button2)
Label1.Select()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
SwapControls(TableLayoutPanel1, ComboBox1, TextBox1)
SwapControls(TableLayoutPanel1, Button2, Button1)
Label1.Select()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.Select()
ComboBox1.SelectedIndex = 0
TextBox1.Text = ComboBox1.SelectedItem
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
TextBox1.Text = ComboBox1.SelectedItem
End Sub
End Class

How to expand combo box on focus event?

I want to automatically expand Combo box on focus event.
I have set the Droppeddown = True in gotfocus event, but this has a side effect. When click event gets fired, it expands dropdown and closes immediately. How can I avoid it?
Here is Code:
Private Sub cmbElectLoadPS_gotfocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbElectLoadPS.GotFocus
cmbElectLoadPS.DroppedDown = True
End Sub
What about check if already DroppedDown ?
Private Sub cmbElectLoadPS_gotfocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbElectLoadPS.GotFocus
if Not cmbElectLoadPS.DroppedDown Then
cmbElectLoadPS.DroppedDown = True
End If
End Sub
If u need this behavior for all your combo controls is better to create your own implementation
Pulic Class CustomComboBox
Inherits ComboBox
Protected Overrides Sub OnEnter(ByVal e As System.EventArgs)
if Not DroppedDown Then
DroppedDown = True
End If
End Sub
End Class
Oh .. add the same value to ComboBox on Mouseup event..
it would do the trick for u :)
sthing like :
private void comboBox1_Enter(object sender, EventArgs e)
{
comboBox1.DroppedDown = true;
}
private void comboBox1_MouseUp(object sender, MouseEventArgs e)
{
comboBox1.DroppedDown = true;
}
Not your best solution.. but it would do the trick :)
Create a timer called tmrDropDown (you should create a timer for each ComboBox) and leave its default properties.
Add this code:
Private Sub cmbBox_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbBox.GotFocus
tmrDropDown.Enabled = True
End Sub
And
Private Sub tmrDropDown_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrDropDown.Tick
cmbBox.DroppedDown = True
tmrDropDown.Enabled = False
End Sub
To implement this features for multiple combobox controls, rather than inheriting the combobox as a new custom control, I'd propose this simple solution:
Private Sub AutoDropDownCombobox_Enter(sender As Object, e As EventArgs) Handles _
cboControl1.Enter, cboControl2.Enter ' register additional events here
If Not CType(sender, ComboBox).DroppedDown Then
CType(sender, ComboBox).DroppedDown = True
End If
End Sub