Saving CheckBox Items to Database Access - vb.net

i have vb.net application form.
It contains ID, Age,Name as Textbox and TC as Checkbox.
I have following code to these items, but checkbox items is saved automatically whether checked or not.
So what to do?
[Imports System.Data.OleDb
Imports System.Data
Public Class Form1
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim con_str As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Satyam\Documents\Database2.accdb"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
con.ConnectionString = con_str
con.Open()
'MsgBox(con.State)
Dim myReader As OleDbDataReader
cmd = New OleDbCommand("select * from Table1", con)
myReader = cmd.ExecuteReader
While myReader.Read()
End While
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub AddTable1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddTable1.Click
Try
con.ConnectionString = con_str
con.Open()
'MsgBox(con.State)
cmd = New OleDbCommand("insert into Table1(ID,Age,Name,TC) values ('" & IDtxt.Text & "','" & Agetxt.Text & "','" & Nametxt.Text & "','" & TCtxt.Text & "')", con)
cmd.ExecuteNonQuery()
MsgBox("Added Successfuly")
Dim myReader As OleDbDataReader
cmd = New OleDbCommand("select * from Table1", con)
myReader = cmd.ExecuteReader
Agetxt.Clear()
While myReader.Read()
End While
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
End Class

Check this code. This is for 3 checkboxes. You can extend it for 10 checkboxes.
Have a look here:
Dim hbStr As String
Dim bgStr As String
Dim tcStr As String
If hb.Checked Then
hbStr = hb.Text
Else
hbStr = ""
End If
If bg.Checked Then
bgStr = bg.Text
Else
bgStr = ""
End If
If tc.Checked Then
tcStr = tc.Text
Else
tcStr = ""
End If
Dim cmd As New OleDbCommand
Dim conn As New OleDbConnection("Connection String")
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "insert into Table1(ID,Age,Name,TC,HB.BG) values ('" & IDtxt.Text & "','" & Agetxt.Text & "','" & Nametxt.Text & "','" & tcStr & "','" & hbStr & "','" & bgStr & "')"
cmd.ExecuteNonQuery()
Hope this helps you.

Sorry it save only TC not Hb.
If Hbtxt.Checked Then
cmd = New OleDbCommand("insert into Table1(ID,Age,Hb) values ('" & IDtxt.Text & "','" & Agetxt.Text & "','" & Hbtxt.Text & "')", con)
Else
cmd = New OleDbCommand("insert into Table1(ID,Age,Hb,) values ('" & IDtxt.Text & "','" & Agetxt.Text & "','')", con)
End If
If TCtxt.Checked Then
cmd = New OleDbCommand("insert into Table1(ID,Age,TC) values ('" & IDtxt.Text & "','" & Agetxt.Text & "','" & TCtxt.Text & "')", con)
Else
cmd = New OleDbCommand("insert into Table1(ID,Age,TC) values ('" & IDtxt.Text & "','" & Agetxt.Text & "','')", con)
End If

Related

Visual Basic 2013 create new Record in Access Execure Error

I am creating a simple UserID/Password access database for a Visual Basic program.
Everything works except adding a new user.
My text box Objects are linked to my database but I keep getting this error when I try to add my new user.
Error: An unhandled exception of type
'System.Data.OleDb.OleDbException' occurred in System.Data.dll
HERE IS MY CODE:
Imports System.Data.OleDb
Public Class newUser
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\PasswordCheck.accdb"
Dim conn As OleDbConnection = New OleDbConnection
Private Sub btnNewUser_Click(sender As Object, e As EventArgs) Handles btnNewUser.Click
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\PasswordCheck.accdb"
Dim conn As OleDbConnection = New OleDbConnection
conn.ConnectionString = connString
conn.Open()
Dim SaveNew As String = "INSERT INTO [Password] (UserId, Password, firstName, LastName) Values ('" & txtUserID.Text & "','" & txtPassword.Text & "','" & txtFirst.Text & "','" & txtLast.Text & "')"
Dim cmd As New OleDbCommand
cmd.Connection = conn
With cmd
.CommandText = SaveNew
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("You have been added to our Database")
txtUserID.Text = ""
txtPassword.Text = ""
txtFirst.Text = ""
txtLast.Text = ""
conn.Close()
End Sub
Private Function SaveNew() As String
Throw New NotImplementedException
End Function
End Class
Password is a reserved word also for a field, so:
Dim SaveNew As String = "INSERT INTO [Password] (UserId, [Password], FirstName, LastName) Values ('" & txtUserID.Text & "','" & txtPassword.Text & "','" & txtFirst.Text & "','" & txtLast.Text & "')"
And further, if UserID not is text, then no quotes:
Dim SaveNew As String = "INSERT INTO [Password] (UserId, [Password], FirstName, LastName) Values (" & txtUserID.Text & ",'" & txtPassword.Text & "','" & txtFirst.Text & "','" & txtLast.Text & "')"
That said, try to explorer how to carry this out using parameters. Much more fun than SQL concatenation.

When Inserting into database only two row in datagridview been save in vb.net

My problem here is every time i want to save into the database, only two row in the datagridview can be save. why is that ? is it because of the two command of inserting ?
Here is my code:
Try
For Each column As DataGridViewRow In dtorder.Rows
Dim sqlconn As New OleDb.OleDbConnection
Dim sqlquery As String
Dim sqlquery1 As String
Dim cmd As New OleDb.OleDbCommand
Dim cmd1 As New OleDb.OleDbCommand
Dim connString As String
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Bloodyjenk\Documents\POS system.accdb"
sqlconn.ConnectionString = connString
sqlconn.Open()
sqlquery = "INSERT INTO OrderedInfoName VALUES ('" & txtOrderNo.Text & "','" & column.Cells(0).Value & "','" & column.Cells(1).Value & "','" & column.Cells(2).Value & "','" & column.Cells(3).Value & "')"
sqlquery1 = "INSERT INTO Ordered VALUES ('" & txtOrderNo.Text & "','" & cmbTable.Text & "','" & cmbOrdertype.Text & "','" & lblDate.Text & "','" & lblStatus.Text & "','" & lblPrice.Text & "','" & lblDiscount.Text & "','" & lblSub.Text & "', 0, 0)"
cmd = New OleDb.OleDbCommand(sqlquery, sqlconn)
cmd1 = New OleDb.OleDbCommand(sqlquery1, sqlconn)
cmd.ExecuteNonQuery()
cmd1.ExecuteNonQuery()
sqlconn.Close()
Next
Catch ex As Exception
MsgBox("DONE")
OrderList.Show()
Me.Close()
End Try

Why error ???? Syntax error in INSERT INTO statement

Public Sub register_user()
Dim con As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\User\Documents\login.mdb")
con.Open()
Dim reg As New DataTable("loginadmin")
Dim aaa As New OleDb.OleDbDataAdapter("Select * from loginadmin ", con)
Dim rs As New OleDb.OleDbCommand("Insert into loginadmin(username,password) values ('" & TextBox1.Text & "', '" & TextBox2.Text & "')", con)
rs.ExecuteNonQuery()
MessageBox.Show("user successfully registerd")
con.Close()
End Sub
'debugger caught this error " syntax error insert into statement"
'the da
try this :- Dim rs As New OleDb.OleDbCommand ("Insert into loginadmin([username],[password]) values ('" & TextBox1.Text & "', '" & TextBox2.Text & "')", con)

insert record in multiple table using sqldataadapter and sqltransaction

I'm trying to insert record in multiple table at a time using sqldataadapter and sqltransaction. i use the following code. but it is not working. help me plz....... tell me the problem in this code
Dim cn As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=AMHSDB;Integrated Security=True")
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim trans As SqlTransaction
Dim tot As Integer
Public Sub RecordSave()
tot = CInt(TB3.Text.Trim) + CInt(TB4.Text.Trim) + CInt(TB5.Text.Trim) + CInt(TB6.Text.Trim)
Dim yr As String
yr = Now.Year()
Try
cn.Open()
trans = cn.BeginTransaction()
da.InsertCommand.Transaction = trans
da.InsertCommand = New SqlCommand("INSERT INTO[FTUT_tbl] (roll_no,s_name,class,session,eng_i,ben,math,stu_wor,gra_tot) VALUES ('" & TB1.Text.Trim & "','" & TB2.Text.Trim & "','Nursery','" & yr & "','" & TB3.Text.Trim & "','" & TB4.Text.Trim & "','" & TB5.Text.Trim & "','" & TB6.Text.Trim & "','" & tot & "')", cn)
da.InsertCommand.ExecuteNonQuery()
da.Dispose()
da.InsertCommand = New SqlCommand("INSERT INTO[FTE_tbl] (roll_no,s_name,class,session) VALUES ('" & TB1.Text.Trim & "','" & TB2.Text.Trim & "','Nursery','" & yr & "')", cn)
da.InsertCommand.ExecuteNonQuery()
da.Dispose()
trans.Commit()
MsgBox("Rocord Successfully Inserted!")
Catch ex As Exception
trans.Rollback()
MsgBox(ex.Message)
Finally
cn.Close()
End Try
End Sub
Create the InsertCommand first, and then assign the transaction:
da.InsertCommand = New SqlCommand("...")
da.InsertCommand.Transaction = trans
And you need to commit your transactions:
da.InsertCommand.Transaction.Commit()
try this, may be it will help for you
Dim dsBillMst As DataTable
Dim TrDtsSvr As SqlTransaction
Dim cmdReadLocal As New SqlCommand
Dim ConSvr As New SqlConnection(gblstrDBConnectionStr)
ConSvr.Open()
TrDtsSvr = ConSvr.BeginTransaction()
cmdReadLocal.Transaction = TrDtsSvr
cmdReadLocal.commandtext="//your insert statement"
cmdReadLocal.executenonquery()
adapter = New SqlDataAdapter(cmdReadLocal)
dsBillMst = New DataTable
adapter.Fill(dsBillMst)
your problem is you disposed the sql command in the first insert, but then you didnt open it again in another insert.
try this one.....
cn.Open()
trans = cn.BeginTransaction()
da.InsertCommand.Transaction = trans
da.InsertCommand = New SqlCommand("INSERT INTO[FTUT_tbl] (roll_no,s_name,class,session,eng_i,ben,math,stu_wor,gra_tot) VALUES ('" & TB1.Text.Trim & "','" & TB2.Text.Trim & "','Nursery','" & yr & "','" & TB3.Text.Trim & "','" & TB4.Text.Trim & "','" & TB5.Text.Trim & "','" & TB6.Text.Trim & "','" & tot & "')", cn)
da.InsertCommand.ExecuteNonQuery()
da.Dispose()
cn.Open()
da.InsertCommand = New SqlCommand("INSERT INTO[FTE_tbl] (roll_no,s_name,class,session) VALUES ('" & TB1.Text.Trim & "','" & TB2.Text.Trim & "','Nursery','" & yr & "')", cn)
da.InsertCommand.ExecuteNonQuery()
da.Dispose()

VB.NET 2010 ADD STATEMENT

i have this code on my ADD button, is there's other way to shorten this statement of code.
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
On Error GoTo ErrSQL
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
'Open connection if it is not yet open
cnn.Open()
End If
cmd.Connection = cnn
'check whether add new update
If Me.txtstdID.Tag & "" = "" Then
'add new
'add data to table
cmd.CommandText = "INSERT INTO inventory (ID,BRAND,SPECIFICATION,STATUS) Values ('" & Me.txtstdID.Text & "','" & Me.cboBrand.Text & "','" & Me.txtDescription.Text & "','" & strStat & "')"
cmd.ExecuteNonQuery()
Else
'update data in table
cmd.CommandText = "UPDATE inventory SET ID =" & Me.txtstdID.Text & ",BRAND='" & Me.cboBrand.Text & "', SPECIFICATION='" & Me.txtDescription.Text & "', STATUS = '" & strStat & "', WHERE ID=" & Me.txtstdID.Text & ""
cmd.ExecuteNonQuery()
End If
'refresh data in list
RefreshData()
'clear form
Me.btnClear.PerformClick()
'close connection
cnn.Close()
Exit Sub
ErrSQL:
MsgBox(Err.Description)
End Sub
There isn't too much to do to shorten the code, there is a lot to do to prevent Sql Injection and parsing problems.
I will try to change your code to this
Try
Using cnn = new OleDbConnection(constring)
Dim cmd As New OleDb.OleDbCommand
cnn.Open()
cmd.Connection = cnn
Dim cmdText as String
'check whether add new update
If Me.txtstdID.Tag & "" = "" Then
cmdText = "INSERT INTO inventory (ID,BRAND,SPECIFICATION,STATUS) " +
"Values (#ID, #Brand, #specs, #stat)"
else
cmdText = "UPDATE inventory SET ID=#ID, BRAND=#Brand,SPECIFICATION=#specs" +
"STATUS = #stat WHERE ID=#ID"
End If
cmd.CommandText = cmdText
cmd.Parametes.AddWithValue("#ID", Me.txtstdID.Text)
cmd.Parametes.AddWithValue("#Brand", Me.cboBrand.Text)
cmd.Parametes.AddWithValue("#specs", Me.txtDescription.Text)
cmd.Parametes.AddWithValue("#stat", strStat)
cmd.ExecuteNonQuery()
End Using
'refresh data in list
RefreshData()
'clear form
Me.btnClear.PerformClick()
Catch(x As Exception)
MsgBox(x.Message)
End Try
I was tempted to remove the redundant SET ID=#ID in the Update statement, but, then you have to add the #ID parameter after the other parameters because in OleDb the parameter order matters