How to do a registerform by ASP.NET VB SQL - sql

I am designing a registerform by vb.net but I don't know how to do this.
The following is my code:
Protected Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
Dim Conn As SqlConnection = New SqlConnection("localdb\v11.0")
Conn.Open()
Dim sqlstr As String = "insert into user_profile(username,password,nickname,realname,email) values('&username.Text&','&password.Text&','&nickname.Text&','&realname.Text&','&email.Text&')"
Dim cmd As New SqlCommand(sqlstr, Conn)
cmd.ExecuteNonQuery()
cmd.Cancel()
Conn.Close()
Conn.Dispose()
End Sub
but there is some errors...
and, is this concept right? If click the button then insert the data into SQL database?

Protected Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
Dim Conn As SqlConnection = New SqlConnection("localdb\v11.0")
Conn.Open()
Dim sqlstr As String = "insert into user_profile(username, password, nickname, realname, email) values('" & username.Text & "','" & password.Text & "','" & nickname.Text & "','" & realname.Text & "','" & email.Text &"')"
Dim cmd As New SqlCommand(sqlstr, Conn)
cmd.ExecuteNonQuery()
cmd.Cancel()
Conn.Close()
Conn.Dispose()
End Sub
You need to build your sqlstr correctly ... use quotes to separate the string from values of text boxes. You are also open to sql injections you should use paramaterised values.

Related

data type mismatch criteria expression in vb.net,access while inserting

Imports System.Data.OleDb
Imports System.IO
Public Class insuranceform
Dim read As String
Dim datafile As String
Dim connstring As String
Dim cmd As New OleDbCommand
Public da As New OleDbDataAdapter
Dim str As String
Public ds As New DataSet
Public ds1 As New DataSet
Public ds2 As New DataSet
Dim myconnection As OleDbConnection = New OleDbConnection
Dim er As Integer
Private Sub insuranceform_Load(sender As Object, e As EventArgs) Handles MyBase.Load
read = "provider=microsoft.ace.oledb.12.0;data source="
datafile = "C:\Users\DELL\source\repos\HRIS SYSTEM\loginformdatabase\BLUESTREAM.accdb"
connstring = read & datafile
myconnection.ConnectionString = connstring
ds.Clear()
DateTimePicker1.Value = DateTime.Now
DateTimePicker2.Value = DateTime.Now
DateTimePicker3.Value = DateTime.Now
If myconnection.State = ConnectionState.Open Then
myconnection.Close()
End If
myconnection.Open()
er = 0
'cn.Open()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
End Sub
Private Sub Save_Click(sender As Object, e As EventArgs) Handles Button1.Click
ds.Clear()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
If er = 0 Then
Try
cmd.Connection = myconnection
cmd.CommandText = "insert into insurancedetail(Name,EmployeeID,PAN,UniversalAccountNumber,AdharNo,CurrentAddress,PermanentAddress,Landline,MartialStatus,MobileNumber,EmergencyContactNo,BloodGroup,DoyouHaveHDFCbankaccount,NameOfdependentmember_F) values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "','" & TextBox7.Text & "','" & TextBox8.Text & "','" & ComboBox2.Text & "','" & TextBox9.Text & "','" & TextBox10.Text & "','" & TextBox11.Text & "','" & ComboBox1.Text & "','" & TextBox12.Text & "')"
cmd.ExecuteNonQuery() 'if command is executed'
Dim result As Integer = MessageBox.Show("New insurance detail Added. Want To Add Another One.", "Added", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
Me.Close()
ElseIf result = DialogResult.Yes Then
ds.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
TextBox11.Clear()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
TextBox17.Clear()
TextBox18.Clear()
TextBox20.Clear()
ComboBox1.ResetText()
ComboBox2.ResetText()
ComboBox3.ResetText()
ComboBox4.ResetText()
ComboBox5.ResetText()
DateTimePicker1.ResetText()
DateTimePicker2.ResetText()
DateTimePicker3.ResetText()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
'insert close
End If
'myconnection close
End Sub
Way too many Class level variables. Especially not myconnection and cmd. What in the world is er? Procedures should not do too much. Move some code off to other procedures, especially if they will be called more than once.
For database objects use Using blocks. They will ensure that your objects are closed and disposed even if there is an error. You don't appear to be using the DataAdapter so just fill a DataTable directly. It can be bound to a DataGridView.
There is no reason to fill the DataTable again before the save. You may want to refill is again after the save.
I am guessing at the datatypes in your database. You must check the database to get the correct datatypes and for string types get the size of the field. Convert your TextBox values to the correct types. I have only used a few of your fields for demonstration purposes. Make sure you add your parameters in the same order that they appear in the sql statement.
Private dt As New DataTable
Private connString As String = "provider=microsoft.ace.oledb.12.0;data source=C:\Users\DELL\source\repos\HRIS SYSTEM\loginformdatabase\BLUESTREAM.accdb"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SetDatePickerValues()
FillDataTable()
End Sub
Private Sub Save_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Using cn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Insert Into insurancedetail(Name,EmployeeID,PAN) Values(#Name, #EmployeeID, #PAN);", cn)
cmd.Parameters.Add("#Name", OleDbType.VarChar, 100).Value = TextBox1.Text
cmd.Parameters.Add("#EmployeeID", OleDbType.Integer).Value = CInt(TextBox2.Text)
cmd.Parameters.Add("#PAN", OleDbType.VarChar, 100).Value = TextBox3.Text
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
FillDataTable()
Dim result As Integer = MessageBox.Show("New insurance detail Added. Want To Add Another One.", "Added", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
Me.Close()
Else
ClearForm()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ClearForm()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
TextBox11.Clear()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
TextBox17.Clear()
TextBox18.Clear()
TextBox20.Clear()
ComboBox1.ResetText()
ComboBox2.ResetText()
ComboBox3.ResetText()
ComboBox4.ResetText()
ComboBox5.ResetText()
SetDatePickerValues()
End Sub
Private Sub FillDataTable()
Try
dt.Clear()
Using cn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Select * From insurancedetail", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub SetDatePickerValues()
DateTimePicker1.Value = DateTime.Now
DateTimePicker2.Value = DateTime.Now
DateTimePicker3.Value = DateTime.Now
End Sub

how to add data in sql database with datagridview

heres my code in adding data to sql database
Dim ConStr As String = "Data Source=SYSTEMS-LAPTOP\DEVSQL;Initial Catalog=ContactDB;Persist Security Info=True;User ID=sa;Password=P#ssw0rd123"
Dim sql As String = "SELECT * FROM dataContactDB"
Dim sqlCon As New SqlConnection
Dim sqlCmd As New SqlCommand
Dim sqlAdapter As SqlDataAdapter
Dim sqlBuilder As SqlCommandBuilder
Dim sqlDataset As DataSet
Dim sqlTable As DataTable
this code loads my data in datagridview from sqldatabase
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
sqlCon = New SqlConnection(ConStr)
sqlCon.Open()
sqlCmd = New SqlCommand(sql, sqlCon)
sqlAdapter = New SqlDataAdapter(sqlCmd)
sqlBuilder = New SqlCommandBuilder(sqlAdapter)
sqlDataset = New DataSet
sqlAdapter.Fill(sqlDataset, "dataContactDB")
sqlTable = sqlDataset.Tables("dataContactDB")
sqlCon.Close()
dgData.DataSource = sqlDataset.Tables("dataContactDB")
dgData.ReadOnly = True
dgData.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
my codes in adding data to sqldatabase
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
sqlCon.Open()
sqlCmd.CommandText = "insert into dataContactDB(con_Name,con_Phone,Address,Company,Gender) values('" & txtName.Text & "','" & txtPhone.Text & "','" & txtAddress.Text & "','" & txtCompany.Text & "','" & txtGender.Text & "')"
sqlCmd.ExecuteNonQuery()
sqlCon.Close()
End Sub
all i want to do is when you add data in sqldatabase. datagridview will retrieve the new added data and add it on its list. every time i add data . datagridview didnt show my recent added data, how do i do that?
You simply have to reload the data in grid. Put all code the in a function named LoadMyGrid, that you have written in frm_load. Now call this method from frm_load. Also call same method in your button click event in the last line.

insertion in vb.net ( it returns syntax error in insert to statement in a textbox)

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New OleDbConnection("provider= microsoft.jet.oledb.4.0;data source=" & CurDir() & "\bilingual1.mdb")
Dim reader As OleDbDataReader
Dim cmd As New OleDbCommand
Try
con.Open()
Dim str As String
str = " insert to yoruba (ọro,itumo,geesi) values ('" & TextBox1.Text & "', '" & RichTextBox1.Text & "', '" & RichTextBox2.Text & "')"
cmd = New OleDbCommand(str, con)
reader = cmd.ExecuteReader
MsgBox("new word added.")
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
You shouldn't need a Reader for an INSERT command. I changed the Cmd method to ExecuteNonQuery() for INSERT command and reformatted the command text for readability.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New OleDbConnection("provider= microsoft.jet.oledb.4.0;data source=" & CurDir() & "\bilingual1.mdb")
Dim cmd As OleDbCommand
Try
con.Open()
Dim str As String
str = "INSERT INTO [yoruba] (ọro,itumo,geesi) VALUES ('" & TextBox1.Text & "', '" & RichTextBox1.Text & "', '" & RichTextBox2.Text & "');"
cmd = New OleDbCommand(str, con)
cmd.ExecuteNonQuery()
con.Close()
MsgBox("new word added.")
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try

How to get count of records in a table?

Someone help me
I am working on our project and I need to check if my DB has already 20 records.
If so, then it will not accept records anymore.
I've been trying the codes below:
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim ds, ds2 As New DataSet
Dim da, da2 As OleDb.OleDbDataAdapter
Dim sql, sql1 As String
Dim int As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
con.ConnectionString = "Provider=Microsoft.jet.OLEDB.4.0; data source = |datadirectory|\Database6.mdb"
con.Open()
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts WHERE Username='" & TextBox1.Text & "'", con)
Dim sdr As OleDb.OleDbDataReader = cmd.ExecuteReader
Dim cmd1 As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts")
sql = "INSERT INTO Accounts ([Username], [Password], [FirstName], [LastName]) VALUES ('" & TextBox1.Text & "','" & TextBox2.Text & "', '" & TextBox3.Text & "','" & TextBox4.Text & "') "
sql1 = "SELECT Count([AccountID]) FROM Accounts"
cmd = New OleDb.OleDbCommand(sql, con)
cmd1 = New OleDb.OleDbCommand(sql1, con)
Convert.ToInt32(sql1)
cmd1.ExecuteScalar()
If sql1 < 20 Then
MsgBox("Cannot accept records")
ElseIf sdr.HasRows = False Then
cmd.ExecuteNonQuery()
MsgBox("Account Added")
ElseIf sdr.HasRows = True Then
MsgBox("Username is taken")
End If
con.Close()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Hide()
Form2.Show()
End Sub
End Class
But the convert code fires an error :
Input string was in incorrect format
But if I delete the convert code it gives me the error
Conversion from string "SELECT Count([AccountID]) FROM A" to type 'Double' is not valid."
Help me please.
TIA
I dont know VB all that well, this is from the top of my head. Your trying to convert your SQL text, which will never work. Try something like this:
dim result as object
result = cmd1.ExecuteScalar()
dim count as int
count = Convert.ToInt32(result)
If count < 20 Then

system.data.oledb.oledbexception:Syntax error in INSERT INTO Statement

I have a Project in VB.NET as follows
Public Class MCARegis
Dim con As New OleDb.OleDbConnection()
Private Sub MCARegis_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim da As OleDb.OleDbDataAdapter
Dim dbprovider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Taher\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\Database1.accdb;Persist Security Info=False;"
Me.con = New OleDb.OleDbConnection()
con.ConnectionString = dbprovider
con.Open()
MsgBox("opened")
End Sub
Private Sub btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadd.Click
Try
Dim da As OleDb.OleDbDataAdapter
Dim dbprovider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Taher\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\Database1.accdb;Persist Security Info=False;"
Me.con = New OleDb.OleDbConnection()
con.ConnectionString = dbprovider
con.Open()
Dim sqlquery As String = "INSERT INTO MCA (URno,SName,Fname,CAddress,)" + "VALUES (" & CInt(txtUrn.Text) & ",'" & txtName.Text & "','" & txtFname.Text & "','" & txtCAdd.Text & "');"
Dim sqlcommand As New OleDb.OleDbCommand(sqlquery)
With sqlcommand
.CommandText = sqlquery
.Connection = con
.ExecuteNonQuery()
End With
MsgBox("Record Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
I am getting an error when i try to add values at the Insert into statement any suggestions on this?
system.data.oledb.oledbexception:Syntax error in INSERT INTO Statement at system.data.oledb.command.exceutecommandtexterrorhandling(oledbhresult hr)
at systems.data.oledb.oledbcommand.executecommandtext(object&executeresult)......
at system.data.oledb.oledbcomamand.executenonquery()
at line 29.
Thanks in Advance....
Replace "INSERT INTO MCA (URno,SName,Fname,CAddress,)" by "INSERT INTO MCA (URno,SName,Fname,CAddress)". You have specified a redundant comma