Ok button in VB.net - vb.net

I have a form that contain a combobox, I'm inserting an error check to check if the user hit the ok button before selecting a valid value from the combobox it mask the error and keep the form on focus, till the user select a proper value, but in my case after raise the error the application still close after i press Ok, would you help me identify my mistake
here is my code
Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
Try
If SymbolComboBox.SelectedValue Is Nothing Then
Throw New Exception()
Else
ErrorProvider1.SetError(SymbolComboBox, String.Empty)
Me.DialogResult = System.Windows.Forms.DialogResult.OK
Me.Close()
End If
Catch ex As Exception
ErrorProvider1.SetError(SymbolComboBox, "Error")
End Try
End Sub
Thank you in advance
Jp

Is your OK button the default accept button for the form ? If so, I beleive it will always return System.Windows.Forms.DialogResult.OK no matter the outcome, unless you specifically cancel the action. I do not remember how to cancel the action though, but if it's the case, I sugesst you remove that AcceptButton property of your form.
OR,
Is it possible that SymbolComboBox.SelectedValue is never 'Nothing' even when nothing is selected (like an empty string) ? I would use selectedIndex instead and check if it's equal to -1.
Hope that helps.

I'm not sure, but I do know that using exceptions like this to control program flow is a bad technique, and in this case unnecessary:
Private Sub OK_Button_Click(ByVal sender As Object, ByVal e As EventArgs)
Handles OK_Button.Click
If SymbolComboBox.SelectedValue Is Not Nothing Then
ErrorProvider1.SetError(SymbolComboBox, String.Empty)
Me.DialogResult = System.Windows.Forms.DialogResult.OK
Me.Close()
Else
ErrorProvider1.SetError(SymbolComboBox, "Error")
End If
End Sub

Why not look at using a required field validator to do this? Are you doing Web forms or Win Forms development? Also what is the value of SymbolComboBox.SelectedValue when you get this issue?

Related

trying to validate user input when exiting textbox in VB

I would think this problem is so simple and basic , I just can't get anything to work. I just want to validate user input and I can never get the validation rules to fire only when I want . I've tried using got focus , lost focus , leave , and validating . Some of those fire when the forms loaded some trigger when other fields look up . There have to be an easy way I hope you can understand and can help. thanks
Please try the following txtName.TextChanged as the event, this will run each time the value is changed in the text box.
Private Sub txtName_TextChanged(sender As Object, e As EventArgs) Handles txtName.TextChanged
End Sub
You can use the .net ErrorProvider and the Validating event.
Private err As New ErrorProvider()
Private Sub TextBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
If TextBox1.Text = "" Then
e.Cancel = True
err.SetError(TextBox1, "This text box cannot be blank.")
Else
err.Clear()
End If
End Sub

vb.net: Distinguish between me.close() and x-button

how is it possible to distinguish between the event, that the user explicitly pressed to x-button (or pressed ALT F4) to close a form and all other methodes of closing the form programatically (me.close(), etc).
I already figured out, that this could be done using sender objects but I don't really get it. Could somebody explain it for me with an example?
Thank you all very much in advance.
The class FormClosingEventArgs event args has an enumeration to tell what the reason the form is closing.
https://msdn.microsoft.com/en-us/library/system.windows.forms.closereason(v=vs.110).aspx
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles Me.Closing
If Not appClosing AndAlso e.CloseReason = System.Windows.Forms.CloseReason.UserClosing Then
' DO WHATEVER CODE YOU WANT IN HERE
' LIKE SETTING E.CANCEL TO TRUE
End If
End Sub
' You can also set a close appClosing local variable at the class level as a boolean, whenever you call closing in code, assign the variable.
appClosing = True
Me.Close();
It's as simple as that. :)
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs)
e.Cancel = True
End Sub
This will prevent the X button to close the form and also the :) .The issue is that if you do this you cannot close your form using Me.Close too , To fix this,just remove the EventHandler :)
RemoveHandler Me.Closing, AddressOf Form1_FormClosing
'Now close the form
Me.Close()

Issue detecting checkbox state in DataGridView

I have a DataGridView control in a .Net application that contains a checkbox column. I would like for the user to be able to edit the checkboxes. The issue that I am running into is that I cannot detect the state of the checkbox after the user checks it.
If the checkbox was originally checked, then it will return checked as soon as the DataGridViewCheckBoxCell gets focus. But, if I click on the checkbox again and unchecks it, then it still returns checked. From that point on, it will always return checked regardless of the actual state of the checkbox until it looses focus and gains it again.
Likewise, if the checkbox was originally unchecked, then when it gets focus it will return unchecked in the click event regardless of what the state of the checkbox actually is.
Here is my code.
Private Sub grdTemplates_CellContentClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdTemplates.CellContentClick
Dim strValue As String = ""
Try
If Me.grdTemplates.Columns(e.ColumnIndex).Name = "colCurrentTemplate" Then
'The user clicked on the checkbox column
strValue = Me.grdTemplates.Item(e.ColumnIndex, e.RowIndex).Value
'THIS VALUE NEVER CHANGES WHILE THE DataGridViewCheckBoxCell HAS FOCUS
Me.lblTemplates.Text = strValue
End If
Catch ex As Exception
HandleError(ex.ToString)
End Try
End Sub
Thanks in advance,
Mike
Include this in your code:
Sub dataGridView1_CurrentCellDirtyStateChanged(ByVal sender As Object, ByVal e As EventArgs) Handles dataGridView1.CurrentCellDirtyStateChanged
If dataGridView1.IsCurrentCellDirty Then
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub
Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.currentcelldirtystatechanged.aspx

Where do I control the behavior of the "X" close button in the upper right of a winform?

I'm venturing into making my VB.NET application a little better to use by making some of the forms modeless.
I think I've figured out how to use dlg.Show() and dlg.Hide() instead of calling dlg.ShowDialog(). I have an instance of my modeless dialog in my main application form:
Public theModelessDialog As New dlgModeless
To fire up the modeless dialog I call
theModelessDialog.Show()
and within the OK and Cancel button handlers in dlgModeless I have
Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
Me.DialogResult = System.Windows.Forms.DialogResult.OK
Me.Hide()
End Sub
Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.Hide()
End Sub
and that seems to work fine.
The "X" button in the upper right is getting me, though. When I close the form with that button, then try to reopen the form, I get
ObjectDisposedException was unhandled. Cannot access a disposed object.
I feel like I'm most of the way there but I can't figure out how to do either of the following:
Hide that "X" button
Catch the event so I don't dispose of the object (just treat it like I hit Cancel)
Any ideas?
The class of this dialog is System.Windows.Forms.Form.
Catch the FormClosing event and, if the reason is UserClosing, set Cancel on the event to true.
Something like the following:
Private Sub Form1_FormClosing(sender as Object, e as FormClosingEventArgs) _
Handles Form1.FormClosing
if e.CloseReason = CloseReason.UserClosing then
e.Cancel = true
Me.Hide()
end if
End Sub
Use Me.Close() to hide the form. To open it, use the following snippet:
If theModelessDialog.IsDisposed Then
theModelessDialog = New dlgModeless
End If
dlgModeless.Show()
If this is saving data, then you'll need to figure some way of storing it (perhaps in a static variable/s in the form). This is the proper way to do what you are trying to achieve though.
You'll also have to forgive me if my VB is off, it's been a while.
the formclosing event allows me to do a managed exit of the form so I have included a question to confirm to exit. I also have a form flag bterminate to force the cancel where i want it to and therefore not ask the question. Thanks your suggestion helped me as well :)
Dim msgboxresponse As MsgBoxResult
If e.CloseReason = CloseReason.UserClosing Then
If Not Me.bTerminate Then
msgboxresponse = MsgBox("Are you sure you want to cancel adding?", _
MsgBoxStyle.Question + MsgBoxStyle.YesNo, Me.Text)
If msgboxresponse <> MsgBoxResult.Yes Then
e.Cancel = True
Return
End If
End If
End If
#John was Hiding the form in his code and the answers above provide a solution to that case. Often, though, you are not planning to use the form again, so you really do want the form to be Disposed. All Close related activities will be in one place if you Handle the FormClosing event using Me.FormClosing by adding it to anyCancel/Close/Exit code that you already have. e.g. in #John's case:
Private Sub Cancel_Button_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Cancel_Button.Click, Me.FormClosing
....More code
Me.Dispose
End Sub
Note the use of the Me.Dispose instead of any existing Me.Close. If you leave the Me.Close you'll create an infinite loop. See this for the subtle differences between Close and Dispose.
Agree with handling the FormClosing event. Or change the properties on the form to hide the system X control.
I've tried everything and it didn't work
if you just want to close, without showing an messagebox, you will just need:
Private Sub FORM1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
>e.Cancel = False
>FORM2.Show() (if you want to show another form)
End Sub
Hope this helps you...!

VB.NET Form Hiding Issue

I have a custom form, B. B is created by A, which has a handle to B.VisibleChanged.
B only has an OK and Cancel button on it, and I want to do some logic when OK is hit.
B's OK button is dealt with like this:
Me.Result = Windows.Forms.DialogResult.OK
Me.Hide()
The code in A is properly hit and run, but it never hides B. When I check the values of the properties on B, it shows me Visible = False.
Does anyone have any suggestions as to the possible cause of this issue?
Edit
This form was shown using the Show() command, as I'm making a later call to have the form flash using FlashWindow().
Not exactly sure about your question.
why not use me.Close() instead of me.Hide?
Is it OK to have multiple instances of B at a time? If not, go for ShowDialog.
If you can rephrase the question, someone can probably resolve your problem.
I suppose you want to display a messagebox with an ok & cancel button. Instead of using a form use a mesagebox.
eg:
DialogResult dgResult = MessageBox.Show("Click Yes or No", "Test App", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (DialogResult.OK == dgResult)
{
//Do what you want.
}
else
{
//Do nothing.
}
If you are going to use a form, to do that & wanted to modify the parent's form, it would be advisable to use delegates to prevent form B from modifying form A's variables.
Else: (Not recommended)
Declare form B as a member variable of form A.
when required instantiate form B.
do B.ShowDialog();
internally in OK & cancel do this.dispose();
Again when you need form B just instantiate. re - instantiation will not be too much of an overhead if you dont call it very often.
But if you only need OK Cancel, use message box instead.
The show/hide approach works for me:
Public Class frmViewChild ' your form A
Private WithEvents _edit As frmEdit
'code
Private Sub editCell()
Dim PKVal As String
Dim PKVal2 As String
Dim fieldOrdinalPos As Integer
Dim isLastField As Boolean
If _edit Is Nothing Then
_edit = New frmEdit
_edit.MdiParent = Me.MdiParent
End If
'code
_edit.init(<params>)
If Not _edit.isNothing Then
_edit.Show()
_edit.WindowState = FormWindowState.Maximized
_edit.BringToFront()
End If
End Sub
'code
Private Sub _edit_VisibleChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles _edit.VisibleChanged
If Not _edit.Visible Then
WindowState = FormWindowState.Maximized ' revert after closing edit form
End If
End Sub
Public Class frmEdit ' your form B
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
Dim ret As Integer
doOK(ret)
If ret > -1 Then ' no error
Me.Hide() ' close form, but didn't cancel
End If
End Sub
HTH