check database connection using background worker - vb.net

I already banging my head with this problem, I use backgroundWorker to check if database is OPEN and here's my code for that:
Public Class Form1
Delegate Sub SetLabelText_Delegate(ByVal [Label] As Label, ByVal [text] As String)
Dim sqlconnection As New SqlConnection("Data Source=" & My.Settings.Server & ";Initial Catalog=" & My.Settings.Database & ";Integrated Security=false;user id=" & My.Settings.Username & ";password=" & My.Settings.Password & ";Connection Timeout=5;")
Dim connectionStatus As String
Private Sub SetLabelText_ThreadSafe(ByVal [Label] As Label, ByVal [text] As String)
If [Label].InvokeRequired Then
Dim MyDelegate As New SetLabelText_Delegate(AddressOf SetLabelText_ThreadSafe)
Me.Invoke(MyDelegate, New Object() {[Label], [text]})
Else
[Label].Text = [text]
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'I store my database information to my.settings then display it on textboxes for manipulation
TextBox1.Text = My.Settings.Server
TextBox2.Text = My.Settings.Database
TextBox3.Text = My.Settings.Username
TextBox4.Text = My.Settings.Password
'just getting my computer name
lblCompName.Text = System.Windows.Forms.SystemInformation.ComputerName
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Try
If sqlconnection.State = ConnectionState.Closed Then
sqlconnection.Open()
connectionStatus = "Online"
'sqlconnection.Open()
SetLabelText_ThreadSafe(Me.Label1, "Database Status: online")
End If
Catch ex As Exception
connectionStatus = "Offline"
sqlconnection.Close()
SetLabelText_ThreadSafe(Me.Label1, "Database Status: offline")
End Try
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Error IsNot Nothing Then
Label1.Text = "Database Status: " & connectionStatus
Else
Label1.Text = "Database Status: " & connectionStatus
End If
BackgroundWorker1.RunWorkerAsync()
End Sub
end class
In my code above it does actually works, it does display "database is online/offline" when restarting my program within the visual studio but when I run the program then turn-off/disable my network connection(my database is on other computer) it always display "Database is ONLINE" but I'm pretty sure that there is already no connection between my pc and database(because I PING it) so it must be display as "Database is oFFLINE".
Did I missed something regarding of using backgroundWOrker? Oh BTW, I'm new in using BackgroundWorker.
Any help or alternative solutions is much appreciated thanks!

Related

vb.net login with sqlite

im trying to create a login form in vb.net with SQLite with this code
Imports System.Data.SQLite
Public Class frmLogin
Private Sub btnlogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlogin.Click
Dim table As DataTable = Nothing
Dim da As New SQLiteDataAdapter("Select * from user_tbl where username='" & txtuser.Text & "'and pass_id='" & txtpass.Text & "'", myconn)
Try
If txtuser.Text = "" And txtpass.Text = "" Then
MessageBox.Show("Please fill Username and Password", "Important", MessageBoxButtons.OK, MessageBoxIcon.Information)
txtuser.Focus()
Else
da.Fill(table)
If table.Rows.Count > 0 Then
frmMain.Show()
Me.Close()
Else
MessageBox.Show("login not successful")
End If
da.Dispose()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ConnectME()
End Sub
End Class
but i keep getting an error at line 26 "da.fill(table)"
Here is what the error says:
Here are two lines of your code:
Dim table As DataTable = Nothing
da.Fill(table)
You have no code in between that assigns an object to that table variable. Why exactly are you surprised that there's an issue here? If I told you to fill a bag and then handed you no bag, how exactly would you go about filling it? You couldn't, because you can't fill a bag that doesn't exist, yet you expect your app to be able to fill a DataTable that doesn't exist.

the connection property has not been initialized

I'm trying to run this code for my user interfaces, I connected the interface with my database and I did everything correctly. But the problem is this error keeps showing and I have no clue in how to fix it.
The error says "the connection property has not been initialized"
And this is my code,
Public Class ManageBus
Private Sub btnclear_Click(sender As Object, e As EventArgs) Handles btnclear.Click
txtbus.Text = Nothing
txtdriver = Nothing
End Sub
Private Sub btnexit_Click(sender As Object, e As EventArgs) Handles btnexit.Click
End
End Sub
Private Sub btnadd_Click(sender As Object, e As EventArgs) Handles btnadd.Click
Try
OracleConnection1.Open()
Dim command As String
command = "insert into BUS(Bus_ID, Driver_ID)" _
& " values('" & txtbus.Text & "', '" _
& txtdriver.Text & ")"
OracleDataAdapter1.InsertCommand.CommandText = command
lblsql.Text = command
OracleDataAdapter1.InsertCommand.ExecuteNonQuery()
MsgBox("Insert Successful", MsgBoxStyle.Information, "Insert Status")
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
OracleConnection1.Close()
End Try
End Sub
You need to initialize the connectionstring for the connection to setup the connection. For example:
Dim OracleConnection1 As New OracleConnection("Data Source=ORCL;User Id=test;Password=test;");
OracleConnection1.Open();

Application with two forms is not showing

I am creating a form application using Visual Studio Express VB 2008 and SQL server 2008. I have two forms. When the program start is not showing me any form. What is to be done that I could use two forms as one program. For example, in one form I want to insert data type state, city .. and the other to use the same information for something else. But like I said, my first step is to see both forms in one program. What should I do to make it work
Imports System.Data.Sql
Imports System.Data.SqlClient
' This is my main form called form1 and through it I want to call a form called Country. Belonging to the same project. How to call a form ,,country,, that I could use
Public Class Form1
Dim objDS As New DataSet
Dim objDA As New SqlDataAdapter
Public Sqlcon As New SqlConnection With {.connectionString = "server=XXX\MSSQL2008;database=TEST;Trusted_Connection=True;"}
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If hasConnection() = True Then
MessageBox.Show("uspijesno povezano sa bazom")
End If
getSelc()
End Sub
Public Function hasConnection() As Boolean
Try
Sqlcon.Open()
Sqlcon.Close()
Return True
Catch ex As Exception
MessageBox.Show("Niste povezani sa bazom")
Return False
End Try
End Function
Public Function selc()
Dim objDS = New DataSet
Dim objDA As New SqlDataAdapter
Sqlcon.Close()
Sqlcon.Open()
Dim exCommand As String = ""
Dim myCommand As New SqlCommand
Dim commitTransaction = Sqlcon.BeginTransaction
Try
myCommand = New SqlCommand("EXECUTE " & "regionSelect" & " '" & txtID.EditValue & "', '" & txtShortN.EditValue & "', N'" & txtRegion.EditValue & "', '" & txtStatus.EditValue & "'", Sqlcon)
myCommand.Transaction = commitTransaction
objDA.SelectCommand = myCommand
objDA.Fill(objDS)
commitTransaction.Commit()
Sqlcon.Close()
MessageBox.Show("Podaci su uspijesno poslati")
Catch ex As Exception
MessageBox.Show(ex.Message)
commitTransaction.Rollback()
End Try
End Function
Private Sub SimpleButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
'insert()
End Sub
Private Sub btnConfirm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfirm.Click
getSelc()
End Sub
Public Function getSelc()
objDS = New DataSet
Dim com As New SqlCommand
Sqlcon.Close()
Sqlcon.Open()
GridControl1.DataSource = Nothing
Try
com = New SqlCommand("EXECUTE rS '" & txtID.Text & " ' , ' " & txtRegion.Text & "' , '" & txtShortN.Text & "', ' " & txtStatus.Text & " ' ", Sqlcon)
'com = New SqlCommand("SELECT * FROM tblRegion", Sqlcon)
objDA.SelectCommand = com
objDA.Fill(objDS)
com.CommandType = CommandType.StoredProcedure
GridControl1.DataSource = objDS.Tables(0)
objDA.Dispose()
com.Dispose()
Sqlcon.Close()
MessageBox.Show("Im here")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
'GridControl1.DataSource = Nothing
'objDS.Tables(0).Rows.Clear()
End Function
Private Sub SimpleButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton4.Click
getSelc()
Dim newRow As DataRow
newRow = objDS.Tables(0).NewRow
newRow.Item(0) = txtID.EditValue
newRow.Item(1) = txtShortN.EditValue
newRow.Item(2) = txtRegion.EditValue
newRow.Item(3) = txtStatus.EditValue
objDS.Tables(0).Rows.Add(newRow)
End Sub
Private Sub SimpleButton3_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton3.Click
End Sub
Private Sub SimpleButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton1.Click
Country.Show() ' => Is this a good way, and is there any better way and more efficient
End Sub
End Class
You cannot load more than one form on Application Startup. You have to load any one form first then show others from its Form_Load event.
Private Sub StartupForm_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim form2 As New Form2
form2.Show()
Dim form3 As New Form3
form3.Show()
End Sub
Or you can load forms manually on Button Click.
Set the Form1 as a StartupForm from the Project Property Window.
Now, Add a button in your first form button1 and write down some code to display another form.
Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
Dim form2 As New Form2
form2.Show()
End Sub
Another one is calling main method. For that you need to assign Main method in your Project Property Window
Module mainModule
Sub Main()
Dim form2 As New Form2
form2.Show()
Dim form3 As New Form3
form3.ShowDialog()
End Sub
End Module

Why is my form disappearing when I press ENTER?

Good-day,
I'm experiencing a very strange event that just started happening. Whenever I press the ENTER button on my keyboard, I expect the KeyDown event of my textbox to be raised and the corresponding code run. Instead, the form disappears (as if the .Hide() method has been called). When I debug, I see that the code that's supposed to run after the KeyDown event is raised is executing accordingly - but the form just disappears.
I've never encountered this before, so I don't know what to do. Any help would be appreciated. Thanks.
HERE'S THE CODE OF MY FORM:
Imports System.Net
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class FormAdd
#Region "VARIABLE DECLARATIONS CODE"
'FOR MySQL DATABASE USE
Public dbConn As MySqlConnection
'FOR CARD NUMBER FORMATTING
Private CF As New CardFormatter
'FOR CARD ENCRYPTION
Dim DES As New System.Security.Cryptography.TripleDESCryptoServiceProvider
Dim Hash As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encryptedCard As String
#End Region
#Region "SUB-ROUTINES AND FUNCTIONS"
Private Sub GetDBdata()
Try
If TextBoxAccount.Text = "" Then
MessageBox.Show("Sorry, you must enter an ACCOUNT# before proceeding!")
TextBoxAccount.Focus()
Else
dbConn = New MySqlConnection
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
End If
dbConn.Open()
Dim dbAdapter As New MySqlDataAdapter("SELECT * FROM customer WHERE accountNumber = " & TextBoxAccount.Text, dbConn)
Dim dbTable As New DataTable
dbAdapter.Fill(dbTable)
If dbTable.Rows.Count > 0 Then
'MessageBox.Show("Customer Account Found!")
Call recordFound()
TextBoxLastName.Text = dbTable.Rows(0).Item("nameLAST")
TextBoxFirstName.Text = dbTable.Rows(0).Item("nameFIRST")
TextBoxSalutation.Text = dbTable.Rows(0).Item("nameSALUTATION")
TextBoxCompanyName.Text = dbTable.Rows(0).Item("nameCOMPANY")
Else
'MessageBox.Show("No Customer Records Found! Please try again!")
Call recordNotFound()
ButtonReset.PerformClick()
End If
dbConn.Close()
End If
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
Dispose()
End Sub
Private Sub SetDBData()
Try
dbConn = New MySqlConnection
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
Dim noCard As Boolean = True
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
End If
dbConn.Open()
Dim dbQuery As String = "SELECT * FROM cc_master WHERE ccNumber = '" & TextBoxCard.Text & "';"
Dim dbData As MySqlDataReader
Dim dbAdapter As New MySqlDataAdapter
Dim dbCmd As New MySqlCommand
dbCmd.CommandText = dbQuery
dbCmd.Connection = dbConn
dbAdapter.SelectCommand = dbCmd
dbData = dbCmd.ExecuteReader
While dbData.Read()
If dbData.HasRows() = True Then
MessageBox.Show("This Credit/Debit Card Already Exists! Try Another!")
noCard = False
Else
noCard = True
End If
End While
dbData.Close()
If noCard = True Then
'PERFORM CARD ENCRYPTION
'PERFORM DATABASE SUBMISSION
Dim dbQuery2 As String = "INSERT INTO cc_master (ccType, ccNumber, ccExpireMonth, ccExpireYear, ccZipcode, ccCode, ccAuthorizedUseStart, ccAuthorizedUseEnd, customer_accountNumber)" & _
"VALUES('" & ComboBoxCardType.SelectedItem & "','" & TextBoxCard.Text & "','" & TextBoxExpireMonth.Text & "','" & TextBoxExpireYear.Text & _
"','" & TextBoxZipCode.Text & "','" & TextBoxCVV2.Text & "','" & Format(DateTimePickerStartDate.Value, "yyyy-MM-dd HH:MM:ss") & "','" & Format(DateTimePickerEndDate.Value, "yyyy-MM-dd HH:MM:ss") & "','" & TextBoxAccount.Text & "');"
Dim dbData2 As MySqlDataReader
Dim dbAdapter2 As New MySqlDataAdapter
Dim dbCmd2 As New MySqlCommand
dbCmd2.CommandText = dbQuery2
dbCmd2.Connection = dbConn
dbAdapter2.SelectCommand = dbCmd2
dbData2 = dbCmd2.ExecuteReader
MessageBox.Show("Credit/Debit Card Information Saved SUCCESSFULLY!")
ButtonReset.PerformClick()
End If
dbConn.Close()
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
Dispose()
End Sub
Private Sub ResetForm()
TextBoxAccount.Clear()
TextBoxLastName.Clear()
TextBoxFirstName.Clear()
TextBoxSalutation.Clear()
TextBoxCard.Clear()
ComboBoxCardType.SelectedItem = ""
TextBoxCompanyName.Clear()
TextBoxCVV2.Clear()
TextBoxExpireMonth.Clear()
TextBoxExpireYear.Clear()
TextBoxZipCode.Clear()
CheckBoxConfirm.Checked = False
TextBoxAccount.SelectionStart = 0
TextBoxAccount.SelectionLength = Len(TextBoxAccount.Text)
TextBoxAccount.Focus()
GroupBoxInputError.Hide()
LabelInstruction.Show()
GroupBox1.Height = 75
End Sub
Private Sub recordFound()
GroupBoxInputError.Text = ""
LabelError.BackColor = Color.Green
LabelError.ForeColor = Color.White
LabelError.Text = "RECORD FOUND!"
GroupBoxInputError.Visible = True
GroupBox1.Height = 345
ButtonReset.Show()
LabelInstruction.Hide()
ComboBoxCardType.Focus()
End Sub
Private Sub recordNotFound()
GroupBoxInputError.Text = ""
LabelError.BackColor = Color.Red
LabelError.ForeColor = Color.White
LabelError.Text = "NO RECORD FOUND!"
GroupBoxInputError.Visible = True
End Sub
'Public Sub encryptCard()
' Try
' DES.Key = Hash.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(My.Settings.Key))
' DES.Mode = System.Security.Cryptography.CipherMode.ECB
' Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = DES.CreateEncryptor
' Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(TextBoxCard.Text)
' TextBoxCard.Text = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
' Catch ex As Exception
' MessageBox.Show("The following error(s) have occurred: " & ex.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
' End Try
'End Sub
#End Region
#Region "TOOLSTRIP MENU CONTROL CODE"
Private Sub ExitAltF4ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitAltF4ToolStripMenuItem.Click
End
End Sub
#End Region
#Region "BUTTON CONTROLS CODE"
Private Sub ButtonExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonExit.Click
FormMain.Show()
Me.Close()
End Sub
Private Sub ButtonReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonReset.Click
Call ResetForm()
End Sub
Private Sub ButtonSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSubmit.Click
Call SetDBData()
Call ResetForm()
End Sub
Private Sub ButtonEncrypt_Click(sender As System.Object, e As System.EventArgs) Handles ButtonEncrypt.Click
End Sub
#End Region
#Region "FORM CONTROLS CODE"
Private Sub FormAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
TextBoxAccount.Focus()
Me.KeyPreview = True
Timer1.Enabled = True
Timer1.Interval = 1
GroupBoxInputError.Hide()
ButtonSubmit.Hide()
ButtonReset.Hide()
GroupBox1.Height = 75
'LabelFooter.Text = "Welcome " & FormLogin.TextBoxUsername.Text() & " | Timestamp: " & Date.Now.ToString
Try
LabelIP.Text = "IP: " & Dns.GetHostEntry(Dns.GetHostName).AddressList(0).ToString
Catch ex As Exception
End Try
'Populate the Card Type combobox with the list of card types from the CardFormatter class
ComboBoxCardType.Items.AddRange(CF.GetCardNames.ToArray)
End Sub
#End Region
#Region "TEXTBOX CONTROLS CODE"
Private Sub TextBoxCard_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBoxCard.GotFocus
TextBoxCard.SelectionStart = 0
TextBoxCard.SelectionLength = Len(TextBoxCard.Text)
Me.Refresh()
End Sub
Private Sub TextBoxCard_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBoxCard.LostFocus
'//CARD VALIDATION//
' This code will check whether the card is a valid number or not. It doesn't check to see if the card is active.
' The code calls on the creditcard function stored in MyModules.vb
Try
If creditcard(TextBoxCard.Text) Then
'MsgBox("Card is Valid")
TextBoxCard.BackColor = Color.GreenYellow
TextBoxCard.ForeColor = Color.Black
GroupBoxInputError.Visible = False
TextBoxCard.Text = CF.GetFormattedString(ComboBoxCardType.Text, TextBoxCard.Text)
Me.Refresh()
Else
BWErrorNotice.RunWorkerAsync()
'MsgBox("Invalid Card")
GroupBoxInputError.Visible = True
TextBoxCard.Focus()
TextBoxCard.Text = TextBoxCard.Text.Replace("-", "")
Me.Refresh()
End If
Catch ex As Exception
End Try
End Sub
Private Sub TextBoxAccount_GotFocus(sender As Object, e As System.EventArgs) Handles TextBoxAccount.GotFocus
TextBoxAccount.SelectAll()
End Sub
Private Sub TextBoxAccount_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBoxAccount.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
If TextBoxAccount.Text <> "" Then
Call GetDBdata()
Else
MsgBox("You must enter an account number!", MsgBoxStyle.Exclamation, "ATTENTION PLEASE!")
TextBoxAccount.Focus()
End If
End If
'If e.KeyCode = Keys.Enter Then
' e.Handled = True
' SendKeys.Send("{Tab}")
'End If
End Sub
Private Sub TextBoxCard_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TextBoxCard.MouseClick
TextBoxCard.SelectionStart = 0
TextBoxCard.SelectionLength = Len(TextBoxCard.Text)
TextBoxCard.Text = TextBoxCard.Text.Replace("-", "")
Me.Refresh()
End Sub
#End Region
#Region "OTHER/MISCELLANEOUS CONTROLS CODE"
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
LabelDateTime.Text = DateTime.Now
End Sub
Private Sub BWErrorNotice_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BWErrorNotice.DoWork
Do While Not creditcard(TextBoxCard.Text)
LabelError.BackColor = Color.Black
System.Threading.Thread.Sleep(500)
LabelError.BackColor = Color.Red
System.Threading.Thread.Sleep(500)
Loop
BWErrorNotice.CancelAsync()
End Sub
Private Sub CheckBoxConfirm_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxConfirm.CheckedChanged
If CheckBoxConfirm.Checked = True Then
ButtonSubmit.Show()
Else
ButtonSubmit.Hide()
End If
End Sub
#End Region
End Class
Although what follows will not likely solve the form disappearance problem, it will resolve a downstream issue:
In GetDBData(), you are assigning accountNumber to the value of TextBoxAcount.Text, which must be enclosed with quotes unless you employ a parameter which I strongly recommend you get in the habit of doing.
Dim dbAdapter As New MySqlDataAdapter("SELECT * FROM customer WHERE accountNumber = " & TextBoxAccount.Text, dbConn)
Parameters offer a number of benefits including implicit type conversions, injection attack prevention, and will sometimes even cure unexpected behaviors.
I figured out the problem. I was calling Dispose() at the end of my GetDBData() function - so the form was getting disposed before execution returned back to the TextBox. I deleted it and all is well again.

Issue Log in vb.Net?

I have a problem with a log in... Well let me explain you my problem, the problem is that i want to create a log in with restrictions, I have some textbox with the binding source property changed to my database. But when I type something that is not in the DataBase the program got freezes, I will post my code, hope you can help me (=
Private Sub KryptonButton1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles KryptonButton1.Click
If txtUser.Text <> UserTextBox.Text Then
While txtUser.Text <> UserTextBox.Text
Me.UsuarioContraseñaBindingSource.MoveNext()
End While
If txtUser.Text = UserTextBox.Text Then
KryptonMessageBox.Show("Welcome")
Else
KryptonMessageBox.Show("Error")
End If
End If
End Sub
Have a closer look at the loop in your code and its exit condition … under what circumstances does the loop exit? What happens otherwise?
In general you need play out and cover all scenarios but you already know the scenario here: your user input is not in the database and the application freezes. This should provide ample hints to find the cause.
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
If txt_user.Text <> vbNullString And txt_pass.Text <> vbNullString Then
Dim chkcmd As New SqlCommand("select * from users where username = '" & txt_user.Text & "' and password = '" & txt_pass.Text & "'", con)
If con.State = ConnectionState.Open Then con.Close()
con.Open()
Dim chkval As SqlDataReader = chkcmd.ExecuteReader
If chkval.Read = True Then
Me.Hide()
Form2.Show()
Else
MsgBox("Invalid key to login!", MsgBoxStyle.Exclamation, "Message")
txt_pass.Clear()
txt_user.Clear()
txt_user.Select()
End If
con.Close()
End If
End Sub