vb.net messagebox click behaves different to enter key - vb.net

net gurus
I have the following piece of code. If I mouse click on the messagebox OK button the code behaves correctly but if I press enter it sets focus back to txtusename but then jumps to txtpassword. Any ideas why?
Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
If String.IsNullOrEmpty(txtUserName.Text) Then
Dim msgResult As DialogResult = MessageBox.Show("User Name required", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning)
If msgResult = DialogResult.OK Then
txtUserName.Focus()
End If
Return
ElseIf String.IsNullOrEmpty(txtPassword.Text) Then
Dim msgResult As DialogResult = MessageBox.Show("Password required", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning)
'MsgBox("Password required", vbOKOnly, vbExclamation)
txtUserName.Select()
txtPassword.Select()
Return
End If

In case there is a value on txtUserName and the txtPassword is null or empty you show a MessageBox. After showing the MessageBox (no matter the user selected) you select the txtUserName and txtPassword. Since you can only select one TextBox, the txtPassword is finally selected.
On the Form the txtUserName is selected first, so the cursor jumps from txtPassword to txtUserName. At the end the txtPassword is selected so the cursor jumps now from txtUserName to txtPassword.
You also using .Select on the ElseIf part. In case you want to set the cursor to the TextBox you need to use .Focus (like on the If part).
You need to remove the txtUserName.Select() on the ElseIf and using .Focus instead of .Select on txtPassword to solve your issue:
Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
If String.IsNullOrEmpty(txtUserName.Text) Then
MessageBox.Show("User Name required", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning)
txtUserName.Focus()
Return
ElseIf String.IsNullOrEmpty(txtPassword.Text) Then
MessageBox.Show("Password required", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning)
txtPassword.Focus()
Return
End If
'more code for database connection.
End Sub

Related

How to use InputBox to move to another form

Here's my code
Private Sub BookButton_Click(sender As Object, e As EventArgs) Handles BookButton.Click
Dim Response = InputBox("Enter Employee ID", "Employee Confirmation", "Employee ID", 500, 700)
If Response = "EmployeeTest" Then
Form2.Show()
Else
MsgBox("Invalid Employee ID, Please Try Again", MsgBoxStyle.Exclamation, "Invalid input")
End If
End Sub
when i run the project, after the I entered the correct input, its back to Form1, nothing happens, the input box closed itself. I want to show Form2 after user entered the correct input

Filter button winform execution event problem

i have a textbox & and a button to filter data in my datagridview box, But i have also given a condition that if the form is under editing mode it should not allow filter.
Now the problem is once i click add new record button & even if i save the record, it always shows exception as the form is is editing mode can't filter.
Private Sub AddnewButton_Click(sender As Object, e As EventArgs) Handles AddnewButton.Click
'MsgBox("you preseed add new button")
Try
With AddnewButton
If .Text = "Add New Record" Then
MSdiesBindingSource.AddNew()
.Text = "Cancel"
Else
RefreshData()
MSdiesDataGridView.ClearSelection()
.Text = "Add New Record"
End If
End With
With Size_in_mgTextBox
If (.CanSelect) Then
.Text = String.Empty
.Select()
End If
End With
IsAddNewRecordInProgress = Convert.ToBoolean(AddnewButton.Text = "Cancel")
Catch ex As Exception
MsgBox("An error occured: " & ex.Message.ToString().ToString(),
MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Add new Record Failed")
End Try
End Sub
Private Sub RefreshData()
Try
'Me.MSdiesBindingSource.Filter = Nothing
MSdiesTableAdapter.Fill(Me.TrialdatabaseDataSet.MSdies)
MSdiesBindingSource.RemoveFilter()
Catch ex As Exception
MsgBox("Refresh Data Error!")
End Try
End Sub
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
'MsgBox("you preseed add new button")
Try
Dim result As DialogResult
result = MessageBox.Show("Confirm Save?", "Save Data", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If (result = DialogResult.Yes) Then
Validate()
MSdiesBindingSource.EndEdit()
TableAdapterManager.UpdateAll(Me.TrialdatabaseDataSet)
MessageBox.Show("The record Has been saved",
"Save Data", MessageBoxButtons.OK, MessageBoxIcon.Information)
RefreshData()
AddnewButton.Text = "Add New Record"
Else
' Exit Sub
Return
End If
Catch ex As Exception
MessageBox.Show("Save Data Failed: " & ex.Message.ToString(),
"Save Data", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub AlertWarningMessage()
'Do not allow search while addign record
MsgBox("The Search Function Is Disabled While Adding New Record",
MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Find Record")
End Sub
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
ToolStripStatusLabel1.Text = "Status"
If IsAddNewRecordInProgress = True Then
AlertWarningMessage()
Exit Sub
End If
If Not String.IsNullOrEmpty(KeywordTextBox.Text) Then
SearchInAccessDatabase(KeywordTextBox.Text.Replace("'", "''"))
Else
RefreshData()
Return
End If
End Sub

ISNUMERIC AND EMPTY STRING

I want to create an application where if someone enters a number, it is entered into a listbox but if someone enters an alphabet or leave the textbox blank, a message box should appear. How to do this? Thanks.
Private Sub btnRecord_Click(sender As Object, e As EventArgs) Handles btnRecord.Click
Dim grade As Double
grade = CDbl(txtGrades.Text)
If grade >= 0 And IsNumeric(grade) = True Then
lstGrades.Items.Add(grade)
txtGrades.Text = " "
ElseIf txtGrades.Text = " " Then
MessageBox.Show("Number cannot be less than 0", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
ElseIf IsNumeric(txtGrades.Text) = False Then
MessageBox.Show("Number cannot be an alphabet", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End Sub
You could simplify your logic and eliminate errors by using TryParse. This method determines if a String can be converted to a Double and returns either True or False along with the converted value:
Private Sub btnRecord_Click(sender As Object, e As EventArgs) Handles btnRecord.Click
Dim grade As Double
If Double.TryParse(txtGrades.Text, grade) Then
lstGrades.Items.Add(grade)
txtGrades.Text = " "
Else
MessageBox.Show("Number cannot be an alphabet", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End Sub

Backgroundworker gives multiple error messages

I have a form with three textboxes in it. In my BackgroundWorker1_DoWork handler I test if any TextBox is empty and launch a MessageBox asking the user to fill in all the TextBoxes. This is done in a Try/Catch block. My problem is two fold. If the TextBoxes aren't filled in the user gets the first MessageBox and then another MessageBox when the Catch exception is thrown...so this would be the second MessageBox the user gets. In my BackGroundWorker1_RunWorkCompleted handler I test if an Exception is thrown. It never acknowledges the error and immediately executes the Else block which will be the third message box the user receives saying "Process complete." The Process Complete should not have been shown.
How do I test if there are any TextBoxes not filled in and if they're not throw 1 MessageBox telling the user to fill in all the TextBoxes? And make my RunWorkerComplete handler acknowledge the ElseIf e.Error IsNot Nothing.
Thank you for your help.
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
BackgroundWorker1.WorkerReportsProgress = True
Try
For Each cntrl As Control In Me.Controls()
If TypeOf cntrl Is TextBox Then
If CType(cntrl, TextBox).Text.Equals(String.Empty) Or (CType(cntrl, TextBox).Text = "") Then
cntrl.BackColor = Color.Yellow
MessageBox.Show("Please enter value in all fields on form" & cntrl.Name.ToString())
cntrl.Focus()
End If
End If
Next
runProgram()
Catch ex As Exception
MessageBox.Show("An error occured while trying to load this application. Please contact Maxine Hammett for assistance " &
vbNewLine & "" & vbNewLine & String.Format("Error: {0}", ex.Message))
End Try
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Cancelled = True Then
MsgBox(" Operation Cancelled ")
ProgressBar1.Value = 0
ElseIf e.Error IsNot Nothing Then
MsgBox("Error in RunWorkerComplete" & e.Error.Message)
Else
MsgBox(" Process Complete ")
Close()
End If
End Sub
Moved the control checking to the execute button. But now I get errors about the text boxes not having a path (one of the text boxes is a path to folder).
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim launchProgram As Boolean = False
While launchProgram = False
For Each cntrl As Control In Me.Controls()
If TypeOf cntrl Is TextBox Then
If CType(cntrl, TextBox).Text.Equals(String.Empty) Or (CType(cntrl, TextBox).Text = "") Then
cntrl.BackColor = Color.Yellow
MessageBox.Show("Please enter value in all fields on form" & cntrl.Name.ToString())
cntrl.Focus()
launchProgram = False
Else
launchProgram = True
End If
End If
Next
End While
If launchProgram = True Then
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
I suggest that you check a single text box a time and show the message if its empty:
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
For Each cntrl As TextBox In Controls.OfType(Of TextBox)
If String.IsNullOrEmpty(cntrl.Text) Then
cntrl.BackColor = Color.Yellow
MessageBox.Show("Please enter value in all fields on form" & cntrl.Name.ToString())
cntrl.Focus()
Return
Else
cntrl.BackColor = SystemColors.Window
End If
Next
BackgroundWorker1.RunWorkerAsync()
End Sub
Or maybe concatenate the names of the empty text boxes in the For..Each block if you really need to prompt the user this way:
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim sb As New StringBuilder
For Each cntrl As TextBox In Controls.OfType(Of TextBox)
If String.IsNullOrEmpty(cntrl.Text) Then
If sb.Length > 0 Then sb.Append(", ")
sb.Append(cntrl.Name)
cntrl.BackColor = Color.Yellow
Else
cntrl.BackColor = SystemColors.Window
End If
Next
If sb.Length > 0 Then
MessageBox.Show("Please enter value in all fields on form" & sb.ToString())
Controls.OfType(Of TextBox).Where(Function(a) String.IsNullOrEmpty(a.Text)).FirstOrDefault?.Focus()
Return
End If
BackgroundWorker1.RunWorkerAsync()
End Sub
Otherwise, run the worker.
Good luck.

validation for specific cell in DataGridView 1

How to do validation for DataGridView row details whether is already exists or not when pass the value form Textbox into DataGridView?
This is my function: argAccount & argPortfolio are Textbox value
Function fnValidateAccountPortfolio(ByVal argAccount As String, ByVal
argPortfolio As String) As Boolean
Try
For Each row As DataGridViewRow In Form1.DataGridView1.Rows
If Not row.IsNewRow Then
MessageBox.Show(row.Cells(0).Value.ToString & " Is Already
Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
Next
Catch ex As Exception
Exit Function
End Try
End Function
Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Handles BtnSave.Click
If fnValidateAccountPortfolio(txtAccount.Text, txtPortfolio.Text) = False
Then
MessageBox.Show("Successfully Saved", "Save", MessageBoxButtons.OK,
MessageBoxIcon.Information)
End If
end sub
Based on the link I provided is this what you are looking for?
Function fnValidateAccountPortfolio(ByVal argAccount As String, ByVal argPortfolio As String) As Boolean
Dim found As Boolean = False
For Each Row As DataGridViewRow In DataGridView1.Rows
For Each cell As DataGridViewCell In Row.Cells
If Not (cell.Value Is Nothing) Then
If (CStr(cell.Value).Trim() = argAccount OR CStr(cell.Value).Trim() = argPortfolio) Then
MessageBox.Show(cell.Value.ToString()) ' You could show the value here just to validate but remove it later.
found = True
Exit For
End If
End If
Next
If (found) Then
Exit For
End If
Next
Return found
End Function
So, you will be calling this function like
if (fnValidateAccountPortfolio("1001","PortfolioHere")) Then
MessageBox.Show("Entry exist already in the DataGrid!!!")
Else
MessageBox.Show("Successfully Saved", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information)
End if