insert data during runtime - vb.net

I have created students attendance management database. I have used sql server and VB12. My problem is I have created 2 datasets from my table. One dataset have register no and name. and other have register no, name,attendance ,total and percent. I successfully added reg no and name using first dataset.using second dataset i have to enter the attendance and find its total and percent for the newly created register no. when i enter the attendance and click my add button I receive a error msg tat + operator is not defined for db null.
I have two button connect and add. My code for buttons are,
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
connetionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\ADMIN\Documents\Visual Studio 2012\Projects\studentattendance\studentattendance\attnd\details.mdf;Integrated Security=True"
connection = New SqlConnection(connetionString)
sql = "select * from entry"
Try
connection.Open()
adapter = New SqlDataAdapter(sql, connection)
adapter.Fill(ds)
connection.Close()
EntryDataGridView.DataSource = ds.Tables(0)
MsgBox("connected")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
connetionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\ADMIN\Documents\Visual Studio 2012\Projects\studentattendance\studentattendance\attnd\details.mdf;Integrated Security=True"
connection = New SqlConnection(connetionString)
sql = "select * from entry"
Try
connection.Open()
adapter = New SqlDataAdapter(sql, connection)
cmdBuilder = New SqlCommandBuilder(adapter)
adapter.Fill(ds)
For i = 0 To ds.Tables(0).Rows.Count - 1
ds.Tables(0).Rows(i).Item(9) = ds.Tables(0).Rows(i).Item(2) + ds.Tables(0).Rows(i).Item(3) + ds.Tables(0).Rows(i).Item(4) + ds.Tables(0).Rows(i).Item(5) + ds.Tables(0).Rows(i).Item(6) + ds.Tables(0).Rows(i).Item(7) + ds.Tables(0).Rows(i).Item(8)
ds.Tables(0).Rows(i).Item(10) = ds.Tables(0).Rows(i).Item(9) / 7
Next
adapter.Update(ds.Tables(0))
connection.Close()
MsgBox("Data updated ! ")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
please help me...

"+ operator is not defined for db null."
It's indeed not defined.
You need to check if the field contains a DBNull value.
IsDBNull(ds.Tables(n).Rows(n).Item(n))
For instance, if the 3'rd and 4'th column has the data type set to Integer:
Dim item2 As Object = ds.Tables(0).Rows(i).Item(2)
Dim item3 As Object = ds.Tables(0).Rows(i).Item(3)
Dim result As Integer = (
If(IsDBNull(item2), 0I, CInt(item2)) +
If(IsDBNull(item3), 0I, CInt(item3))
)
You should turn Option Strict ON ASAP as this will prevent you from doing this kind of mistakes in the future.

Related

Save a DataGridView data to Access database

I am trying to save a DataGridView data to an Access database (database is already connected to Visual Studio).
Here's my code:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Try
Dim cn As OleDbConnection
cn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= |DataDirectory|\GEFORSERVI V2.1.accdb;")
cn.Open()
Dim cmd As New OleDbCommand
cmd.Connection = cn
cmd.CommandType = Data.CommandType.Text
Dim Strcommandtext As String = "inserto into Factura(Designacao,PrecoUnitario,Qtd,Total,Nome,Entidade,NIF,Telefone,Morada,CodigoProduto,DataEmissao) VALUES(#Servico_Produto,#Valor,#Qtd,#Total,#Nome,#Entidade,#NIF,#Telemovel,#Bairro,#Data_de_Emissao)"
Dim values As String = ""
For i As Integer = 0 To Factura2DataGridView.Rows.Count - 1
values = Strcommandtext & Factura2DataGridView.Rows(i).Cells(11).Value & ")"
cmd.CommandText = values
cmd.ExecuteNonQuery()
Next i
cmd = Nothing
cn.Close()
MsgBox("Your Record Inserted Successfully ")
Catch myException As Exception
MsgBox("No Record Inserted" + myException.ToString())
Finally
'MsgBox("Closing Connection")
End Try
End Sub
Connections and Commands need to be disposed so they can release unmanaged resources. Using...End Using blocks are the best way to handle this since the will do this even if there is an error. In this code I both the connection and command are included in the Using block. Note the comma at the end of the first Using line.
Pass the CommandText and the Connection directly to the constructor of the command. I noticed you had missed one of the parameters that was in the field list. I also noticed the you typed "inserto". I believe it must be "Insert". It is not necessary to set CommandType since CommandType.Text is the default.
In OleDb the order that the parameters appear in the sql string must match the order that they are added to the Parameters collection.
Build the parameters collection once outside the loop. It is only the Values of the parameters that change in the loop.
Open the connection once, outside the loop.
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Try
Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= |DataDirectory|\GEFORSERVI V2.1.accdb;"),
cmd As New OleDbCommand("Insert into Factura(Designacao,PrecoUnitario,Qtd,Total,Nome,Entidade,NIF,Telefone,Morada,CodigoProduto,DataEmissao)
VALUES(#Servico_Produto,#Valor,#Qtd,#Total,#Nome,#Entidade,#NIF,#Telemovel,#Bairro,#CodigoProduto,#Data_de_Emissao)", cn)
With cmd.Parameters
.Add("#Servico_Produto", OleDbType.Integer)
.Add("#Valor", OleDbType.VarWChar)
.Add("#Qtd", OleDbType.Integer)
.Add("#Total", OleDbType.Decimal)
.Add("#Nome", OleDbType.VarWChar)
.Add("#Entidade", OleDbType.VarWChar)
.Add("#NIF", OleDbType.VarWChar)
.Add("#Telemovel", OleDbType.VarWChar)
.Add("#Bairro", OleDbType.VarWChar)
.Add("#CodigoProduto", OleDbType.Integer)
.Add("#Data_de_Emissao", OleDbType.Date)
End With
cn.Open()
For i As Integer = 0 To Factura2DataGridView.Rows.Count - 1
cmd.Parameters("#Servico_Produto").Value = Factura2DataGridView.Rows(i).Cells(0).Value
cmd.Parameters("#Valor").Value = Factura2DataGridView.Rows(i).Cells(1).Value
cmd.Parameters("#Qtd").Value = Factura2DataGridView.Rows(i).Cells(2).Value
cmd.Parameters("#Total").Value = Factura2DataGridView.Rows(i).Cells(3).Value
cmd.Parameters("#Nome").Value = Factura2DataGridView.Rows(i).Cells(4).Value
cmd.Parameters("#Entidade").Value = Factura2DataGridView.Rows(i).Cells(5).Value
cmd.Parameters("#NIF").Value = Factura2DataGridView.Rows(i).Cells(6).Value
cmd.Parameters("#Telemovel").Value = Factura2DataGridView.Rows(i).Cells(7).Value
cmd.Parameters("#Bairro").Value = Factura2DataGridView.Rows(i).Cells(8).Value
cmd.Parameters("#CodigoProduto").Value = Factura2DataGridView.Rows(i).Cells(9).Value
cmd.Parameters("#Data_de_Emissao").Value = Factura2DataGridView.Rows(i).Cells(10).Value
cmd.ExecuteNonQuery()
Next
End Using
MsgBox("Your Record Inserted Successfully ")
Catch myException As Exception
MsgBox("No Record Inserted" + myException.Message)
End Try
End Sub
There are easier ways to do this. If you have a DataTable bound to the DataGridView you can use a DataAdpater.Update method.

how to display data in text box in vb.net using sql

Private Sub BtnReturn_Click(sender As Object, e As EventArgs) Handles btnReturn.Click
If BorrowAccession.Text = "" Or txtBorrowerstype.Text = "" Then
MsgBox("All fields are required.", MsgBoxStyle.Exclamation)
ElseIf txtremarks.Text = "Over Due" Then
sql = "Select * From `maintenance` fine ='" & txtfine.Text & "' "
reloadtxt(sql)
End sub
how will i display the fine in txtfine.text from my maintenance database after it satisfy the condition from txtremarks. i tried some youtube tutorials but only displaying it from data grid .. want i basically want is directly display it from database to textbox. btw im newbie in vb programming thank you in advance
for my reloadtxt this is the code.
Public Sub reloadtxt(ByVal sql As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sql
End With
dt = New DataTable
da = New MySqlDataAdapter(sql, con)
da.Fill(dt)
Catch ex As Exception
' MsgBox(ex.Message & "reloadtxt")
Finally
con.Close()
da.Dispose()
End Try
End Sub
To populate an object with data from a database you need to access the objects text property.
Textbox1.Text = "Some Text, static or dynamic"
Since you are pulling the data from a datatable you would access the column named "fine" and put that value in the textbox.text property.
Textbox1.Text = dt.row(0).item("fine").tostring
Changed Or to OrElse because it short circuits the If and doesn't have to check the second condition if the first condition is True.
In the reloadtxt method you filled a DataTable and did nothing with it. I changed it to a Function that returns the DataTable. The connection and command are now included in a Using...End Using block so they are closed and disposed even if there is an error.
Never concatenate strings to build an sql statement. Always used parameters.
Private Sub BtnReturn_Click(sender As Object, e As EventArgs) Handles btnReturn.Click
If BorrowAccession.Text = "" OrElse txtBorrowerstype.Text = "" Then
MsgBox("All fields are required.", MsgBoxStyle.Exclamation)
ElseIf txtremarks.Text = "Over Due" Then
Dim dt = reloadtxt()
DataGridView1.DataSource = dt
End If
End Sub
Public Function reloadtxt() As DataTable
Dim dt As New DataTable
Using con As New MySqlConnection("Your connection string"),
cmd As New MySqlCommand("Select * From maintenance Where fine = #Fine", con)
cmd.Parameters.Add(#Fine, MySqlDbType.VarChar, 50).Value = txtfine.Text
Try
con.Open()
dt.Load(cmd.ExecuteReader)
Catch ex As Exception
MsgBox(ex.Message & "reloadtxt")
End Try
End Using
Return dt
End Function

Using VS 2017 and VB to connect to a database

First of, I am a beginner.
more clarification:
I am writing this program in Vis. Basic to access a database, get values and save the info.
the database is a MS Access 2016 database.
I have multiple forms and on each form different values are entered.
I now made an ADD form to write all the data from all the forms in my database.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim sqlconn As New OleDb.OleDbConnection
Dim sqlquery As New OleDb.OleDbCommand
Dim connString As String
Dim custname, custnum, cgender, pkind, pmodel, probear, meduse, tint, tinl, crema, cneed As String
Dim byear As Integer
connString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Users\rolf\source\repos\AMEST_Audiology\AMEST_Audiology\bin\Debug\audiology.accdb"
sqlconn.ConnectionString = connString
sqlquery.Connection = sqlconn
sqlconn.Open()
sqlquery.CommandText = "INSERT INTO audiodat (custName,Custnum,cgender,pkind,pmodel,probear,meduse,tint,tinl,crema,cneed) Values (#custName,#custnum,#cgender,#pkind,#pmodel,#probear,#meduse,#tint,#tinl,#crema,#cneed)"
custname = FrmCust.custName
custnum = FrmCust.Custnum
cgender = FrmCust.CGender
byear = FrmCust.byear
pkind = FrmCust.pkind
pmodel = FrmCust.pmodel
probear = Frmhistory.probear
meduse = Frmhistory.meduse
tint = Frmhistory.tint
tinl = Frmhistory.tinl
crema = FrmClinic.crema
cneed = Frmsolution.cneed
sqlquery.Parameters.AddWithValue("#custname", custname)
sqlquery.Parameters.AddWithValue("#custnum", custnum)
sqlquery.Parameters.AddWithValue("#cgender", cgender)
sqlquery.Parameters.AddWithValue("#pkind", pkind)
sqlquery.Parameters.AddWithValue("#pmodel", pmodel)
sqlquery.Parameters.AddWithValue("#probear", probear)
sqlquery.Parameters.AddWithValue("#meduse", meduse)
sqlquery.Parameters.AddWithValue("#tint", tint)
sqlquery.Parameters.AddWithValue("#tinl", tinl)
' sqlquery.Parameters.AddWithValue("#oprobhis", oprobhis)
sqlquery.Parameters.AddWithValue("#crema", crema)
sqlquery.Parameters.AddWithValue("#cneed", cneed)
sqlquery.ExecuteNonQuery()
sqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Frmprintdoc.Show()
Me.Close()
End Sub
it works as far as the String goes, but i cant save numbers or checkbox state.
it also does NOT actually write the data into the database, just into the memory of the tableadapter. what am i missing???

Compare db value with textbox value VB

My Table
I load the windows user name to textbox1.text using 'System.Environment'
After that I query this and compare the textbox value to the PersonName in db
if it matches, I want to get the relevant Department name ie if it's 'manager'
then I want to display a form from menuitem_click event. My code is below
it dosent work can some one please help with this.
Private Sub MySamplesToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles MySamplesToolStripMenuItem.Click
Dim cn As New SqlClient.SqlConnection("Data Source=ffff;Initial Catalog=ffff;User ID=****;Password=****;")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Dim ta As String
Try
cn.Open()
Dim sql As String
sql = "select * from dbo.Person where [PersonName] ='" + TextBox1.Text + "'"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
ta = reader.Item("Department")
If ta = 'Maneger' Then
Form2.Show()
End If
' TextBox2.Text = reader.Item("Department")
'TextBox2.Text = reader.Item("dob")
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
No matter how you spell it, Manager or Maneger, just make sure what is in the database matches what is in your If statement. I think I would use a drop down box for you to select the Department wherever you are inserting the Person so the Department name would match.
The Using...End Using blocks ensure that you database objects are closed and disposed even if there is an error.
You can pass your Sql statement and the connection directly to the constructor of the command. If all you need is the Department then don't drag down all the date with "*".
Never concatenate strings to build Sql statements. A hacker could type in TextBox1 "Joe; Drop Table dbo.Person;" Using parameters stops this hole because the .Value of the parameter is treated as only a value not executable code.
You are only expecting one value in return so you can use .ExecuteScalar which returns the first column of the first row in the result set.
Your code is very fragile because I suspect you could have duplicate names unless you require unique user names.
Private Sub MySamplesToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles MySamplesToolStripMenuItem.Click
Try
Using cn As New SqlClient.SqlConnection("Data Source=ffff;Initial Catalog=ffff;User ID=****;Password=****;")
Using cmd As New SqlClient.SqlCommand("Select Department From dbo.Person Where PersonName = #Name;", cn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = TextBox1.Text
cn.Open()
Dim ta As String = cmd.ExecuteScalar.ToString
If ta = "Maneger" Then
Form2.Show()
End If
TextBox2.Text = ta
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

insert or update with single button in vb.net

how to insert and update data in database(sql server) with single button in vb.net i tried but not get the result.
here is my code.......
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Try
Dim reader As SqlDataReader
Dim query As String
Dim n As Integer
n = 0
sqlcom1 = New SqlCommand("select * from mydatabase.masters")
sqlcom1.ExecuteReader()
sqlcom = New SqlCommand("select * from mydatabase.masters")
sqlcom.ExecuteReader()
reader = sqlcom1.ExecuteReader
reader = sqlcom.ExecuteReader
sqlcom = New SqlCommand("Update masters SET EmpName=#EmpName, Age=#Age, Address=#Address where Empid=#Empid", conn)
sqlcom.Parameters.Add("#EmpName", SqlDbType.VarChar).Value = TextBox4.Text
sqlcom.Parameters.Add("#Age", SqlDbType.Int).Value = TextBox3.Text
sqlcom.Parameters.Add("#Address", SqlDbType.VarChar).Value = TextBox2.Text
sqlcom.Parameters.Add("#Empid", SqlDbType.Int).Value = TextBox1.Text
sqlcom1 = New SqlCommand("insert into masters(Empid, EmpName, Age, Address) values(#Empid, #EmpName, #Age, #Address)", conn)
sqlcom1.Parameters.AddWithValue("#Empid", TextBox1.Text)
sqlcom1.Parameters.AddWithValue("#EmpName", TextBox4.Text)
sqlcom1.Parameters.AddWithValue("#Age", TextBox3.Text)
sqlcom1.Parameters.AddWithValue("#Address", TextBox2.Text)
conn.Open()
While reader.Read
n = n + 1
End While
If table.Rows.Count = n Then
sqlcom1.ExecuteNonQuery()
ElseIf table.Rows.Count = n + 1 Then
sqlcom.ExecuteNonQuery()
End If
Catch ex As Exception
MessageBox.Show("error" + ex.Message)
End Try
End Sub
Using block ensures that your connection object is closed and disposed even if there is an error.
Normally I put comments in line but the code got so cluttered that had to move most of them up here. I hope you can figure out where they belong.
Dim reader As SqlDataReader - Unused
Dim query As String - Unused
Integers are automatically initialized to zero
Pass the query and the connection to the constructor of the command.
Your connection string will tell SQL Server what database to use. It is not necessary in the query.
Apparently all you want is the count, not all the data.
This query is exactly the same as sqlcom1
Dim sqlcom As New SqlCommand("select * from mydatabase.masters", cn)
sqlcom.ExecuteReader()
You did this twice
reader = sqlcom1.ExecuteReader
Not necessay, we already retrieved the count
`While reader.Read
n = n + 1
End While`
I made the assumption that table was a DataTable populated at some other time. Using the count as comparison to the count in the table is not a great way to determine if the command is Insert or Update but it might work as long as database and table were not used with a DataAdapter that updated the database.
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Try
Dim n As Integer
Using cn As New SqlConnection("Your connection string")
Dim sqlcom1 As New SqlCommand("select Count(*) from masters", cn)
cn.Open()
n = CInt(sqlcom1.ExecuteScalar) 'n is now the number of rows in the database table
Dim sqlcom As New SqlCommand
sqlcom.Parameters.Add("#EmpName", SqlDbType.VarChar).Value = TextBox4.Text
'Age is not a good idea to enter in a database. It changes over time.
'Enter the birth date and calculate the age as needed.
sqlcom.Parameters.Add("#Age", SqlDbType.Int).Value = CInt(TextBox3.Text)
sqlcom.Parameters.Add("#Address", SqlDbType.VarChar).Value = TextBox2.Text
If table.Rows.Count > n Then
'Normally EmpId would be an auto increment (identity) field
'and would NOT be included in an insert.
sqlcom.CommandText = "insert into masters(EmpName, Age, Address) values(#EmpName, #Age, #Address)"
Else
sqlcom.CommandText = "Update masters SET EmpName=#EmpName, Age=#Age, Address=#Address where Empid=#Empid"
sqlcom1.Parameters.Add("#Empid", SqlDbType.Int).Value = CInt(TextBox1.Text)
End If
sqlcom.ExecuteNonQuery()
End Using
Catch ex As Exception
MessageBox.Show("error" + ex.Message)
End Try
End Sub
On second thought, forget the whole thing. Use a DataGridView and a DataAdapter. Then you can just use Update and it will update, insert and delete.