'Else' must be preceded by a matching 'If' or 'ElseIf' - vb.net

I cant run my program due to this error. Can somebody help me? Thanks.
Public Class Login
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If tbx_username.Text <> "" And tbx_pass.Text <> "" Then
Dim SM As New SubjectMaintenance
Dim dr = SM.openSel(SqlString.getSQLSelect(Account.tablename, Account.si_data_username & "='" & tbx_username.Text & "' and " & Account.si_data_pwd & "='" & tbx_pass.Text & "'"), CommandType.Text)
While dr.Read
GUI.accnt.pData_id = dr(Account.si_data_id)
Me.Hide()
GUI.Show()
**Else**
GUI.accnt.pData_pwd = dr(Account.si_data_pwd)
GUI.accnt.pData_username = dr(Account.si_data_username)
GUI.accnt.pData_lname = dr(Account.si_data_lname)
GUI.accnt.pData_fname = dr(Account.si_data_fname)
GUI.accnt.pData_mname = dr(Account.si_data_mname)
End While
SM.closeConDr()
If GUI.accnt.pData_id > 0 Then
MessageBox.Show("Login Failed!")
End If
End If
End Sub
End Class

You cannot put an else inside while end-while, the if-else-end if and while-end while are standalone statements, so you can mix them as follows:
while
if
else
end if
end while
or
if
while
end while
else
while
end while
end if
The only way to break into a nested statement is the GoTo statement, it moves the instruction pointer unconditionally to the specified label.

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If tbx_username.Text <> "" And tbx_pass.Text <> "" Then
Dim SM As New SubjectMaintenance
Dim dr = SM.openSel(SqlString.getSQLSelect(Account.tablename, Account.si_data_username & "='" & tbx_username.Text & "' and " & Account.si_data_pwd & "='" & tbx_pass.Text & "'"), CommandType.Text)
While dr.Read
GUI.accnt.pData_id = dr(Account.si_data_id)
Me.Hide()
GUI.Show()
End While
**Else** 'Try moving the else below the end while or above the while
GUI.accnt.pData_pwd = dr(Account.si_data_pwd)
GUI.accnt.pData_username = dr(Account.si_data_username)
GUI.accnt.pData_lname = dr(Account.si_data_lname)
GUI.accnt.pData_fname = dr(Account.si_data_fname)
GUI.accnt.pData_mname = dr(Account.si_data_mname)
SM.closeConDr()
If GUI.accnt.pData_id > 0 Then
MessageBox.Show("Login Failed!")
End If
End If
End Sub
'Try moving the else below the end while or above the while

Related

Debugging in vb.net?

I'm new to coding, I've been working on my project of online billing system using Visual Basic.
The complete coding has been done, but while running the code, the totalitems and totalamt is not being calculated. Can you please debug or guide me how can I resolve this issue...
It shows errors like
1.conversion of type dbnull to string is not valid
2.string or binary data would be truncated.
Public Class billing
Dim disAmount As Double
Dim getProducID As Integer
Dim getStocks As Integer
Dim validatestock As Integer
Dim getUnitPrice As Double
Dim loadqty As Double
Dim discount As Boolean
Private Sub billing_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
getTransactionID()
GenerateInvoiceNo()
fillComboproduct()
End Sub
Private Sub getTransactionID()
Try
Dim trans As New Random
Dim numbers As Integer = trans.Next(1, 1000000)
Dim digitss As String = numbers.ToString("000000")
txttrans.Text = digitss
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub GenerateInvoiceNo()
lblInvoice.Text = "INV-" & GetUniqueKey(8)
End Sub
Public Shared Function GetUniqueKey(ByVal maxSize As Integer) As String
Dim chars As Char() = New Char(61) {}
chars = "123456789".ToCharArray()
Dim data As Byte() = New Byte(0) {}
Dim crypto As New RNGCryptoServiceProvider()
crypto.GetNonZeroBytes(data)
data = New Byte(maxSize - 1) {}
crypto.GetNonZeroBytes(data)
Dim result As New StringBuilder(maxSize)
For Each b As Byte In data
result.Append(chars(b Mod (chars.Length)))
Next
Return result.ToString()
End Function
Private Sub fillComboproduct()
Dim query As String = "Select productname From product order by productname"
Dim dtproduct As DataTable = getDataTable(query)
txtproductame.DataSource = dtproduct
txtproductame.DisplayMember = "productname"
' txtproductame.ValueMember = "productID"
If txtproductame.Items.Count > 0 Then
txtproductame.SelectedIndex = 0
End If
End Sub
Private Sub clear()
txtproductID.Text = ""
txtprice.Text = ""
txtQuantity.Text = ""
txtBalance.Text = ""
txttotal.Text = ""
txtAmtPaid.Text = ""
lblSubTotal.Text = "0"
txtproductame.Text = ""
lblTotalAmount.Text = "0.00"
lblSubTotal.Text = "0.00"
lblTotalItems.Text = "0"
txtprice.Text = ""
txtQuantity.Text = "1"
txttotal.Text = "0.00"
End Sub
Private Sub addbills()
Try
Sql = "INSERT INTO bills VALUES( '" & txtproductID.Text & "', '" & txtproductame.Text & "','" & txtQuantity.Text & "', '" & txtprice.Text & "','" & txttotal.Text & "', '" & lblInvoice.Text & "', '" & Date.Today & "')"
ConnDB()
cmd = New SqlCommand(sqL, conn)
Dim i As Integer
i = cmd.ExecuteNonQuery
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
Private Sub loadbills()
Try
Sql = "SELECT productID,productname,qty,unitprice FROM bills WHERE invoiceno = '" & Trim(lblInvoice.Text) & "' "
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
dgw.Rows.Clear()
Do While dr.Read = True
dgw.Rows.Add(dr(0), dr(1), dr(2), dr(3))
Loop
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub totalamt()
Try
Sql = "SELECT sum(totalamt) FROM bills where invoiceno = '" & Trim(lblInvoice.Text) & "' "
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While dr.Read = True
lblTotalAmount.Text = dr(0)
Loop
Catch ex As Exception
End Try
End Sub
Private Sub gettotalitems()
Try
Sql = "SELECT sum(qty) FROM bills where invoiceno = '" & Trim(lblInvoice.Text) & "' "
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While dr.Read = True
lblTotalItems.Text = dr(0)
Loop
Catch ex As Exception
End Try
End Sub
Private Sub saveitems()
Try
Sql = "INSERT INTO transactionDetails VALUES('" & txttrans.Text & "','" & lblInvoice.Text & "', '" & lblTotalItems.Text & "', '" & lblTotalAmount.Text & "', '" & txtAmtPaid.Text & "','" & txtBalance.Text & "', '" & cmdpayment.Text & "', '" & Date.Today & "')"
ConnDB()
cmd = New SqlCommand(sqL, conn)
Dim i As Integer
i = cmd.ExecuteNonQuery
If i > 0 Then
MsgBox("Billing Details Successfully saved", MsgBoxStyle.Information, "Saves Billing Details")
Else
MsgBox("Failed in Saves Billing Details", MsgBoxStyle.Information, "Saves Billing Details")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
Private Sub txtproductame_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtproductame.SelectedIndexChanged
Try
ConnDB()
Dim da As New SqlDataAdapter(("select * from product where productname ='" & Trim(txtproductame.Text) & "'"), conn)
Dim dt As New DataTable
da.Fill(dt)
If dt.Rows.Count > 0 Then
Me.txtprice.Text = dt.Rows(0).Item("unitprice") & ""
Me.txtproductID.Text = dt.Rows(0).Item("productID") & ""
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub txtQuantity_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtQuantity.TextChanged
txttotal.Text = Val(txtQuantity.Text) * Val(txtprice.Text)
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Me.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
getTransactionID()
GenerateInvoiceNo()
End Sub
Private Sub BindToText()
Try
With dgw
lblSubTotal.Text = Val(.SelectedRows(0).Cells("qty").Value) * Val(.SelectedRows(0).Cells("price").Value)
.SelectedRows(0).Cells("amt").Value = lblSubTotal.Text
End With
Catch ex As Exception
End Try
End Sub
Private Sub dgw_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgw.CellClick
BindToText()
End Sub
Private Sub dgw_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgw.SelectionChanged
BindToText()
End Sub
Private Sub txtAmtPaid_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtAmtPaid.KeyPress
Dim ch As Char = e.KeyChar
If Char.IsLetter(ch) Then 'Ristricting To Input Only Digits(any number)
e.Handled = True
End If
End Sub
Private Sub txtQuantity_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtQuantity.KeyPress
Dim ch As Char = e.KeyChar
If Char.IsLetter(ch) Then 'Ristricting To Input Only Digits(any number)
e.Handled = True
End If
End Sub
Private Sub btnload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnload.Click
Try
txttotal.Text = Val(txtprice.Text) * Val(txtQuantity.Text)
If txtproductame.Text = "" Or txtQuantity.Text = "" Then
MsgBox("Please enter a product Or Quantity before you click load button")
Else
addbills()
loadbills()
totalamt()
gettotalitems()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
txttotal.Text = ""
txtQuantity.Text = ""
End Sub
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
If dgw.Rows.Count = 0 Then
MsgBox("Please load drugs in the cart before saving", MsgBoxStyle.Exclamation, "Validation")
Exit Sub
End If
If txtAmtPaid.Text = "" Then
MsgBox("Please fill-in Amount Paid by Customer", MsgBoxStyle.Information, "Validation")
txtAmtPaid.Focus()
Exit Sub
ElseIf cmdpayment.Text = "" Then
MsgBox("Please choose Payment status field", MsgBoxStyle.Information, "Validation")
cmdpayment.Focus()
Exit Sub
End If
saveitems()
'DecreaseStocksOnhand()
'UpdateToDecreaseStocksOnHand()
btnreceipt.Show()
getTransactionID()
' GenerateInvoiceNo()
dgw.Rows.Clear()
' btnreceipt.Show()
End Sub
Private Sub Deleteitem()
Try
Sql = "DELETE * FROM bills WHERE productID = '" & dgw.SelectedRows(0).Cells("productID").Value & "'"
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While dr.Read = True
dgw.Rows.Add(dr(0), dr(1), dr(2), dr(3))
Loop
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
Private Sub btnremove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnremove.Click
If MsgBox("Are you sure you want to remove this Product from Cart", MsgBoxStyle.YesNo, "Validation") = MsgBoxResult.Yes Then
Deleteitem()
loadbills()
gettotalitems()
totalamt()
clear()
txttotal.Text = ""
txtQuantity.Text = ""
End If
End Sub
Private Sub txtAmtPaid_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAmtPaid.TextChanged
txtBalance.Text = Val(lblTotalAmount.Text) - Val(txtAmtPaid.Text)
End Sub
Private Sub cmdpayment_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdpayment.SelectedIndexChanged
If cmdpayment.SelectedIndex = 1 Then
txtAmtPaid.Text = "0"
End If
End Sub
Private Sub btnreceipt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnreceipt.Click
receipt.lblInvoice.Text = lblInvoice.Text
receipt.Show()
End Sub
End Class

VB.net - If 1 then "Yes" if 0 then "no"

I have Database Software I am trying to make. The problem is I can't seem to find how to make this work, i'm new to this whole thing and have figured a lot out on my own but I can't seem to do this simple task?
I have a listView that displays the data from the SQl everything works great EXCEPT I need the dropdaown box the say yes or no but import into the SQL database a 1 or 0 and also in my list view i need it to display a Yes or a No instead of a 1 or a 0 ? Thanks IN Advance
Code:
Imports System.Data.SqlClient
Imports System.Data
Public Class cmListAll
Dim cn As New SqlConnection
Dim cmd As SqlCommand
Dim dr As SqlDataReader
Private Sub frmReg_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With Me.cboActive
.Items.Add("Yes")
.Items.Add("No")
.SelectedIndex = 0
End With
Call connectMeToSQLServer("Data Source=Database;Initial Catalog=db_XXX;Integrated Security=False;Uid=sa; Pwd=PASS;")
Call showList()
End Sub
Private Sub cboActive_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
e.Handled = True
End Sub
Private Sub cboACTIVE_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.txtCredentials.Focus()
End Sub
Sub connectMeToSQLServer(ByVal cnString As String)
Try
With cn
If .State = ConnectionState.Open Then .Close()
.ConnectionString = cnString
.Open()
End With
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
Function INC() As Boolean
For Each t In Me.GroupBox2.Controls
If TypeOf t Is TextBox Or TypeOf t Is ComboBox Then
End If
If t.Text = "" Then
INC = True
End If
Next
End Function
Sub showList()
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Select * from [Case Managers]"
dr = cmd.ExecuteReader
Me.ListView1.Items.Clear()
While dr.Read
With Me.ListView1
.Items.Add(dr(0))
With .Items(.Items.Count - 1).SubItems
.Add(dr(1))
.Add(dr(2))
.Add(dr(3))
.Add(dr(4))
End With
End With
End While
dr.Close()
End Sub
Sub clearMe()
For Each t In Me.GroupBox2.Controls
If TypeOf t Is TextBox Then
If t.Text <> "" Then
t.text = ""
End If
Me.cmdNew.Enabled = True
Me.cmdSave.Text = "&Save"
Me.cmdSave.Enabled = False
Me.cmdDelete.Enabled = False
Me.cboActive.SelectedIndex = 0
End If
Next
End Sub
Private Sub cmdNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNew.Click
For Each t In Me.GroupBox2.Controls
If TypeOf t Is TextBox Then
If t.Text <> "" Then
t.text = ""
End If
End If
Next
Me.cmdNew.Enabled = False
Me.cmdSave.Tag = "SAVE"
Me.cmdSave.Text = "&Save"
Me.cmdSave.Enabled = True
Me.GroupBox2.Enabled = True
Me.txtfirstname.Focus()
End Sub
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
Select Case Me.cmdSave.Tag
Case "SAVE"
If INC() = True Then
MsgBox("Please Complete All Fields!", MsgBoxStyle.Exclamation, "")
Exit Sub
Else
cmd = New SqlCommand
cmd.CommandText = "Insert Into [Case Managers](Firstname,Lastname,Credentials,Active) Values('" & Me.txtfirstname.Text & "', '" & Me.txtlastname.Text & "', '" & Me.txtCredentials.Text & "', '" & Me.cboActive.Text & "' )"
cmd.Connection = cn
cmd.ExecuteNonQuery()
MsgBox("Successfully Save!", MsgBoxStyle.Information, "")
End If
Case Else
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Update [Case Managers] Set firstname='" & Me.txtfirstname.Text & "', lastname='" & Me.txtlastname.Text & "', credentials='" & Me.txtCredentials.Text & "', active='" & Me.cboActive.Text & "' Where CaseMangerID = " & Me.ListView1.SelectedItems(0).Text & ""
cmd.ExecuteNonQuery()
MsgBox("Successfully Updated!", MsgBoxStyle.Information, "")
End Select
clearMe()
showList()
End Sub
Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Select * from [Case Managers] Where CaseMangerID = " & Me.ListView1.SelectedItems(0).Text & " "
dr = cmd.ExecuteReader
dr.Read()
Me.txtfirstname.Text = dr(1)
Me.txtlastname.Text = dr(2)
Me.txtCredentials.Text = dr(3)
Me.cboActive.Text = dr(4)
dr.Close()
Me.GroupBox2.Enabled = True
Me.cmdSave.Enabled = True
Me.cmdSave.Tag = "UPDATE"
Me.cmdSave.Text = "&Update"
Me.cmdDelete.Enabled = True
End Sub
Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
If MsgBox("Delete This Record?", MsgBoxStyle.Question + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Delete from [Case Managers] Where CaseMangerID =" & Me.ListView1.SelectedItems(0).Text & " "
cmd.ExecuteNonQuery()
MsgBox("Successfully Deleted!", MsgBoxStyle.Information, "")
Me.cmdDelete.Enabled = False
Me.cmdSave.Enabled = False
Call clearMe()
Call showList()
Else
Exit Sub
End If
End Sub
I assume you're looking at this line:
Me.cboActive.Text = dr(4)
? That's the only thing that looked to me like it might be displaying a yes/no field. You could just put a simple If/Else block there, but as there are several other significant flaws in how this code is structured, I thought it would be useful to re-write that whole method for you:
Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
'Would be better to specify column names here
Dim sql As String = "Select * from [Case Managers] Where CaseMangerID = #CaseManager"
'Best practices in most cases call for creating a new connection object for each query
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(sql, cn)
'This is how to do string substitution in sql to protect against sql injection
cmd.Parameters.Add("#CaseManager", SqlDbType.Int).Value = CInt(Me.ListView1.SelectedItems(0).Text)
Using dr As SqlDataReader = cmd.ExecuteReader()
dr.Read()
Me.txtfirstname.Text = dr(1)
Me.txtlastname.Text = dr(2)
Me.txtCredentials.Text = dr(3)
Me.cboActive.Text = If(dr(4)=0,"No","Yes")
dr.Close()
End Using
End Using 'No need to close the connection. The Using block takes care of it
'The old code would have the left the connection open if an exception was thrown,'
' which could eventually lock you out of the database
Me.GroupBox2.Enabled = True
Me.cmdSave.Enabled = True
Me.cmdSave.Tag = "UPDATE"
Me.cmdSave.Text = "&Update"
Me.cmdDelete.Enabled = True
End Sub
You'll need to do something similar later on to invert this for updates/inserts.
You can use DisplayMember/ValueMember pair:
Dim dict As New Dictionary(Of Integer, String)
dict.Add(0, "No")
dict.Add(1, "Yes")
With Me.cboActive
.DisplayMember = "Value"
.ValueMember = "Key"
.DataSource = dict.ToList()
.SelectedIndex = 0
End With
Dictionary may not the best choice of class here, but works as a proof of concept.
Then just use cboActive.SelectedValue and pass that to the SQL query.

Why does loop doesnt stop at .showdialog in formloadevent

Hello here is a very strange bug I cannot solve. I have a while loop in my formload that looks this way :
While loginOK = False And pstop = False
LoginForm1.ShowDialog()
If NewReg = True Then
While RegErfolgreich = False
Registrierung.ShowDialog()
Dim con As New SqlConnection(My.Settings.SLXADRIUMDEVConnectionString)
con.Open()
Dim cmd = New SqlCommand("Insert Into sysdba.PL_Userverwaltung (Benutzername, Passwort, [E-Mail-Adresse], Profil_OK) Values('" & RegBenutzername & "', '" & RegPassword & "', '" & RegEMailAdresse & "', 'f')", con)
If cmd.ExecuteNonQuery() = 1 Then
My.Settings.Benutzername = RegBenutzername
My.Settings.Passwort = RegPassword
My.Settings.Save()
Me.Close()
RegErfolgreich = True
Else
MsgBox("Es ist ein Fehler aufgetreten.")
End If
End While
Else
NewReg = False
End If
End While
The problem is that after closing loginform1 he jumps back in the loop, and when he starts looping again he opens loginform1 and closes it instantly. and loops again in the while loop.
That means I have a endless loop, which shows the loginform1 and closes it a millisecond later.
One thing to mention is that a friend of mine opened my project in an older vs studio version and this mysterious bug doesnt happen??
Hope for input cheers
EDIT:
Here is loginform1 code
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
If UsernameTextBox.Text <> "" And PasswordTextBox.Text <> "" Then
Startseite.LoginUsername = UsernameTextBox.Text
Startseite.LoginPassword = PasswordTextBox.Text
Startseite.loginOK = True
Me.Close()
Else
MsgBox("Bitte Benutzername und Passwort eingeben!")
End If
End Sub
Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
Startseite.pstop = True
Me.Close()
End Sub
Private Sub LoginForm1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If My.Settings.Benutzername <> "" And My.Settings.Passwort <> "" Then
'MsgBox(My.Settings.Benutzername & " " & My.Settings.Passwort)
UsernameTextBox.Text = My.Settings.Benutzername
PasswordTextBox.Text = My.Settings.Passwort
End If
End Sub
Private Sub lblNeuRegistrieren_Click(sender As Object, e As EventArgs) Handles lblNeuRegistrieren.Click
Startseite.NewReg = True
Me.Close()
End Sub
About your error, probably you didn't initialize your startseite variable to be your main form, loginOK And pstop never get changed and that's why the loop never stops. But on the rest of your code, some general tips.
This is unnecesary
If NewReg = True Then
''
Else
NewReg = False
End If
If NewReg is not true, then it's false by definition. Should be
If NewReg Then
''
End If
Also, overloading the showDialog on loginForm1 is a better solution than adding a yourmainclass object on the second form. It is easier to debug and provides better reusability.
try exiting loop on message box
If cmd.ExecuteNonQuery() = 1 Then
My.Settings.Benutzername = RegBenutzername
My.Settings.Passwort = RegPassword
My.Settings.Save()
Me.Close()
RegErfolgreich = True
Else
MsgBox("Es ist ein Fehler aufgetreten.")
Exit While
End If

vb.net how do i add a new rows (and update) from datagridview programmatically to sql database

asking a new question with regards to my previous problem.
so this is how it goes,
so far i was able make the following code to work (thanks to #JADE for helping me out, (a lot ) :)
Dim connstr As String = "server=midtelephone\sqlexpress; database=testdb; user= sa; password=sa;"
cmdconn = New SqlConnection
cmd = New SqlCommand
cmdconn.ConnectionString = connstr
cmd.Connection = cmdconn
cmdconn.Open()
Dim period, VOUCH_AMT, INDIVIDUAL_AMT, check_no, D_MAILED, DIR_NO As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
With Me.DataGridView1.Rows(i)
If IsDBNull(.Cells(0).Value()) OrElse .Cells(0).Value() Is Nothing OrElse .Cells(0).Value().ToString().Trim() = "" Then
period = ""
Else
period = .Cells(0).Value()
End If
If IsDBNull(.Cells(1).Value()) OrElse .Cells(1).Value() Is Nothing OrElse .Cells(1).Value().ToString().Trim() = "" Then
VOUCH_AMT = "0"
Else
VOUCH_AMT = .Cells(1).Value()
End If
If IsDBNull(.Cells(2).Value()) OrElse .Cells(2).Value() Is Nothing OrElse .Cells(2).Value().ToString().Trim() = "" Then
INDIVIDUAL_AMT = "0"
Else
INDIVIDUAL_AMT = .Cells(2).Value()
End If
If IsDBNull(.Cells(3).Value()) OrElse .Cells(3).Value() Is Nothing OrElse .Cells(3).Value().ToString().Trim() = "" Then
check_no = ""
Else
check_no = .Cells(3).Value()
End If
If IsDBNull(.Cells(4).Value()) OrElse .Cells(4).Value() Is Nothing OrElse .Cells(4).Value().ToString().Trim() = "" Then
D_MAILED = ""
Else
D_MAILED = .Cells(4).Value()
End If
If IsDBNull(.Cells(5).Value()) OrElse .Cells(5).Value() Is Nothing OrElse .Cells(5).Value().ToString().Trim() = "" Then
DIR_NO = ""
Else
DIR_NO = .Cells(5).Value()
End If
End With
cmd.CommandText = "insert into tobee.EBD_BILLHISTORY(period, vouch_amt, individual_amt, check_no, d_mailed, dir_no)values" & _
"('" & period.Replace("'", "''") & "'," & VOUCH_AMT & "," & INDIVIDUAL_AMT & ",'" & check_no.Replace("'", "''") & "','" & D_MAILED.Replace("'", "''") & "', '" & DIR_NO.Replace("'", "''") & "')"
cmd.ExecuteNonQuery()
MsgBox("Saved")
Next
cmdconn.Close()
End Sub
now the problem is if i want to add new rows programmatically (i already set the dgv to edit programmatically ). what are the metrics or the next procedures to do? i have an edit button which enables the datagridview to be edited, something like this:
Private Sub btnEditmain_Click(sender As Object, e As EventArgs) Handles btnEditmain.Click
DataGridView1.AllowUserToAddRows = True
DataGridView1.BeginEdit(True)
btnSave.Enabled = True
End Sub
( also, as i check the table in my database, it seems that there's no changes made after clicking the save button ) pls. help me. thanks in advance. :)
Did you try to change the DataGridView to ListView and enable editing on ListView ?
The insert,edit and delete buttons will appear on the ListView if you have specified their commands respectively.
I wanted to do the same but after long research this was the best. Load the table code then add a button once they edit the DataGridView.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.TableAdapter.Fill(Me.DataSet.YourTable)
Me.TableAdapter.Fill(Me.DataSet.YourTable)
DataGridView1.[ReadOnly] = False
adap.Fill(dt)
BindingSource.DataSource = dt
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
adap.Update(dt)
' adap.UpdateCommand(dt)
' MessageBox.Show("Saved successfully")
Catch ex As Exception
' MessageBox.Show("Error updating database")
End Try

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.