i want to update my datagridview and also my database im new to vb and i dont know what im doing wrong can sombody help me?
Private Sub DataGridView_Booking_Update(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView_Booking.RowLeave
Try
con.Open()
Using cmd As New SqlCommand("UPDATE Tbl_booking SET Omschrijving = #Omschrijving, Jaar = #Jaar, Opmerking = #Opmerking ,Sortnr = #Sortnr)", con)
cmd.Parameters.Add("#Omschrijving", SqlDbType.VarChar)
cmd.Parameters.Add("#Jaar", SqlDbType.Int)
cmd.Parameters.Add("#Opmerking", SqlDbType.VarChar)
cmd.Parameters.Add("#Sortnr", SqlDbType.Int)
cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records")
Finally
con.Close()
End Try
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim con As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\database1.accdb;Persist Security Info=False;")
con.Open()
Dim cmd As New OleDb.OleDbCommand("INSERT INTO table1(name,age,class) VALUES('John Legend','22','B.A Part 1')", con)
cmd.ExecuteNonQuery()
MsgBox("Record inserted successfully.")
con.Close()
Catch
MsgBox("Error Occured.")
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Try
Dim con As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\database1.accdb;Persist Security Info=False;")
con.Open()
Dim cmd As New OleDb.OleDbCommand("update table1 set name='John DOE',age='23',class='12th' where id='1'", con)
cmd.ExecuteNonQuery()
MsgBox("Record Updated Successfully.")
con.Close()
Catch
MsgBox("Error Occured.")
End Try
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Try
Dim con As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\database1.accdb;Persist Security Info=False;")
con.Open()
Dim cmd As New OleDb.OleDbCommand("Delete from table1 where name='John DOE'", con)
cmd.ExecuteNonQuery()
MsgBox("Record Deleted Successfully.")
con.Close()
Catch
MsgBox("Error Occured.")
End Try
End Sub
Private Sub DataGridView1_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
Me.Validate()
Me.dbDataAdapter.Update(Me.dbdataset.Tables("MyTable"))
Me.dbDataSet.AcceptChanges()
End Sub
Related
I want the code to not allow the complete button to work because the column of "StartTime" is null.
Attached is the code below:
Imports System.Data.SqlClient
Imports System.Data
Imports System.IO
Public Class Etask
Dim con As SqlConnection
Dim cmd As SqlCommand
Private Sub Etask_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Labelname.Text = login.mname
Dim str As String = "Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true"
Dim con As New SqlConnection(str)
Dim com As String = "SELECT TaskID, Name, TaskAssigned, StartTime, FinishTime, Status
FROM dbo.Tasks
WHERE Name = '" & Labelname.Text & "'"
Dim Adpt As New SqlDataAdapter(com, con)
Dim ds As New DataSet()
Adpt.Fill(ds, "PosTable")
DataGridView1.DataSource = ds.Tables(0)
End Sub
Private Sub Etask_Resize(sender As Object, e As EventArgs) Handles Me.Resize
Panel1.Left = (Me.Width - Panel1.Width) / 2
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
refreshDGV()
End Sub
Public Sub refreshDGV()
Labelname.Text = login.mname
Dim str As String = "Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true"
Dim con As New SqlConnection(str)
Dim com As String = "SELECT TaskID, Name, TaskAssigned, StartTime, FinishTime, Status
FROM dbo.Tasks
WHERE Name = '" & Labelname.Text & "'"
Dim Adpt As New SqlDataAdapter(com, con)
Dim ds As New DataSet()
Adpt.Fill(ds, "PosTable")
DataGridView1.DataSource = ds.Tables(0)
End Sub
'complete button
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New SqlConnection("Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true")
Dim query As String = "update Tasks set FinishTime=#FinishTime,Status=#Status where TaskID=#id"
con.Open()
cmd = New SqlCommand(query, con)
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = LabelID.Text
cmd.Parameters.Add("#FinishTime", SqlDbType.VarChar).Value = Label1.Text
cmd.Parameters.Add("#Status", SqlDbType.VarChar).Value = comboboxstatus.Text
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Successfully updated!")
refreshDGV()
End Sub
Private Sub FillByToolStripButton_Click(sender As Object, e As EventArgs)
Try
Me.TasksTableAdapter.FillBy(Me.RestaurantDatabaseDataSet2.Tasks)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Me.LabelID.Text = DataGridView1.Item(0, i).Value
End Sub
Private Sub btnstart_Click(sender As Object, e As EventArgs) Handles btnstart.Click
Dim con As New SqlConnection("Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true")
Dim query As String = "update Tasks set StartTime=#StartTime,Status=#Status where TaskID=#id"
con.Open()
cmd = New SqlCommand(query, con)
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = LabelID.Text
cmd.Parameters.Add("#StartTime", SqlDbType.VarChar).Value = Label1.Text
cmd.Parameters.Add("#Status", SqlDbType.VarChar).Value = "Working on it!"
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Successfully started!")
refreshDGV()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.Text = Date.Now.ToString("dd MMM yyyy hh:mm:ss")
End Sub
End Class
This is what the application looks like:
I want the code to check for null data in the StartTime column. If its null, then the complete button won't work. Button1 is the button to complete a task.
ExecuteNonQuery returns an integer with the number of rows affected.
If you create the query so that it does not do an update if the column is NULL, then it will return 0, which you can check for.
Also, it is easier to put the connection string in just one place, so that if you need to change it you only have to do so once - it is too easy to miss an occurrence of the string and have to go and edit it again. Often, such data is stored in the settings for the program, but I've made it as a constant for this example:
Public Const CONNSTR As String = "Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true"
'....
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim query As String = "UPDATE Tasks
SET FinishTime = #FinishTime, Status = #Status
WHERE TaskID = #id
AND StartTime IS NOT NULL"
Dim nRowsAffected = 0
Using con As New SqlConnection(CONNSTR),
cmd As New SqlCommand(query, con)
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = LabelID.Text
cmd.Parameters.Add("#FinishTime", SqlDbType.VarChar).Value = Label1.Text
cmd.Parameters.Add("#Status", SqlDbType.VarChar).Value = comboboxstatus.Text
con.Open()
nRowsAffected = cmd.ExecuteNonQuery()
End Using
If nRowsAffected = 0 Then
MsgBox("Database not updated - check for empty StartTime.")
Else
MsgBox("Successfully updated!")
End If
refreshDGV()
End Sub
The Using statement makes sure that "unmanaged resources" are released when it is done.
Does anyone have an idea on how to update the actual access datbase file? This is my code so far and I think everything is right, but when hit the button to send the information to the actual database file it does not appear in there. Can someone help me with this? The access file I'm talking about is the one outside of the visual basic project itself, but still connected.
Code
Imports System.Data.OleDb
Public Class Form1
Dim provider As String
Dim datafile As String
Dim connString As String
Dim con As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source=G:\Music Session Database\Music Database.accdb")
Dim ds As New DataSet
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
Private Sub btnexit_Click(sender As Object, e As EventArgs) Handles btnexit.Click
Me.Close()
End Sub
Private Sub btnsubmit_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnsubmit1.Click
Me.Music_DatabaseTableAdapter.Insert(Me.songTitle.Text, Me.songArtist.Text, Me.songAlbum.Text, Me.yearReleased.Text)
Me.Music_DatabaseTableAdapter.Fill(Me.Music_DatabaseDataSet.Music_Database)
con.Open()
MsgBox("Record Added")
con.Close()
songTitle.Text = ""
songArtist.Text = ""
songAlbum.Text = ""
yearReleased.Text = ""
End Sub
Private Sub btnsumbit2_Click(sender As Object, e As EventArgs) Handles btnsumbit2.Click
Me.Play_SessionTableAdapter.Insert(Me.songTitle.Text, Me.songArtist.Text, Me.songAlbum.Text, Me.yearReleased.Text, Me.datePlayed.Text, Me.timePlayed.Text, Me.genre.Text)
Me.Play_SessionTableAdapter.Fill(Me.Music_DatabaseDataSet.Play_Session)
con.Open()
MsgBox("Record Added")
con.Close()
songTitle.Text = ""
songArtist.Text = ""
songAlbum.Text = ""
yearReleased.Text = ""
datePlayed.Text = ""
timePlayed.Text = ""
genre.Text = ""
End Sub
Private Sub btnsubmit3_Click(sender As Object, e As EventArgs) Handles btnsubmit3.Click
Me.Song_Artist_InformationTableAdapter.Insert(Me.songArtist.Text, Me.genre.Text, Me.origin.Text, Me.artistInformation.Text)
Me.Song_Artist_InformationTableAdapter.Fill(Me.Music_DatabaseDataSet.Song_Artist_Information)
con.Open()
MsgBox("Record Added")
con.Close()
songArtist.Text = ""
genre.Text = ""
origin.Text = ""
artistInformation.Text = ""
End Sub
Private Sub btnclear_Click(sender As Object, e As EventArgs) Handles btnclear.Click
songTitle.Clear()
songArtist.Clear()
songAlbum.Clear()
yearReleased.Clear()
datePlayed.Clear()
timePlayed.Clear()
genre.Clear()
artistInformation.Clear()
End Sub
Private Sub FillByToolStripButton_Click(sender As Object, e As EventArgs)
Try
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Music_DatabaseBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles Music_DatabaseBindingNavigatorSaveItem.Click
Me.Validate()
Me.Music_DatabaseBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.Music_DatabaseDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Music_DatabaseDataSet.Song_Artist_Information' table. You can move, or remove it, as needed.
Me.Song_Artist_InformationTableAdapter.Fill(Me.Music_DatabaseDataSet.Song_Artist_Information)
'TODO: This line of code loads data into the 'Music_DatabaseDataSet.Play_Session' table. You can move, or remove it, as needed.
Me.Play_SessionTableAdapter.Fill(Me.Music_DatabaseDataSet.Play_Session)
'TODO: This line of code loads data into the 'Music_DatabaseDataSet.Music_Database' table. You can move, or remove it, as needed.
Me.Music_DatabaseTableAdapter.Fill(Me.Music_DatabaseDataSet.Music_Database)
End Sub
Private Sub btnupdate1_Click(sender As Object, e As EventArgs) Handles btnupdate1.Click
Me.Validate()
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from [Music Database]", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
da.Fill(dt)
Music_DatabaseDataGridView.DataSource = dt.DefaultView
da.Update(dt)
End Sub
Private Sub btnupdate2_Click(sender As Object, e As EventArgs) Handles btnupdate2.Click
Me.Validate()
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from [Play Session]", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
da.Fill(dt)
Play_SessionDataGridView.DataSource = dt.DefaultView
da.Update(dt)
End Sub
Private Sub btnupdate3_Click(sender As Object, e As EventArgs) Handles btnupdate3.Click
Me.Validate()
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from [Song Artist Information]", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
da.Fill(dt)
Song_Artist_InformationDataGridView.DataSource = dt.DefaultView
da.Update(dt)
End Sub
End Class
Format of the initialization string does not conform to specification
The connString you create is not valid.
provider = "Microsoft.ACE.OLEDB.12.0"
datafile = "H:\Music Session Database\Music Database.accdb"
connString = provider & datafile
Console.WriteLine(connString)
shows
Microsoft.ACE.OLEDB.12.0H:\Music Session Database\Music Database.accdb
What you want to do is something like
connString = String.Format("Provider={0};Data Source={1}", provider, datafile)
which produces
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Music Session Database\Music Database.accdb
I having some trouble. I have a datagridview that shown all the data from database sql server. But when i try to insert and save the new row one or multiple data in datagridview, the data from previous insert that shown in datagridview from database inserted again along with my new row data.
I just wanted to insert and save the new row data not along with my previous data.
Please help me!
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
cmd = New SqlCommand("Insert into DataSK values (#NIK, #Name, #Address, #Email, #Status)", con)
cmd.Parameters.Clear()
cmd.Parameters.Add("#NIK", SqlDbType.VarChar, 20).Value = dgv.Rows(row).Cells("NIK").Value
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = dgv.Rows(row).Cells("Name").Value
cmd.Parameters.Add("#Address", SqlDbType.VarChar, 50).Value = dgv.Rows(row).Cells("Address").Value
cmd.Parameters.Add("#Email", SqlDbType.Char, 50).Value = dgv.Rows(row).Cells("Email").Value
cmd.Parameters.Add("#Status", SqlDbType.VarChar, 10).Value = dgv.Rows(row).Cells("Status").Value
cmd.ExecuteNonQuery()
End Sub
Something like this should get you going.
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source=ServerName;Initial Catalog=YourDatabaseName;Trusted_Connection=True;"
connection = New SqlConnection(connetionString)
sql = "Select * from Products"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'NOTE: for this code to work, there must be a PK on the Table
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
hi I'm trying to insert a row to my database but I still get this error message (see below):
I used the methode using to be sure that the connection will be closed.
below the script for the insert button :
Private Sub MTB_Insert_Click(sender As Object, e As EventArgs) Handles MTB_Insert.Click
cmd = New SQLite.SQLiteCommand
Using con As New SQLite.SQLiteConnection(constr)
Try
'con.ConnectionString = constr
con.Open()
cmd.Connection = con
cmd.CommandText = "Insert Into Material_Type (Material_Type,Material_Type_Description) values(#Type,#Description)"
cmd.Parameters.AddWithValue("#Type", MTTB_Material_Type.Text)
cmd.Parameters.AddWithValue("#Description", MTTB_Material_Description.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Successful Added Data")
'Calling function load data
loadDatadg1()
'con.Dispose()
'con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
other parts of my code :
Public Class F_Update
Dim con As SQLite.SQLiteConnection
Dim cmd As SQLite.SQLiteCommand
Dim da As SQLite.SQLiteDataAdapter
Dim constr As String = "Data source =Database1.db"
Public Sub loadDatadg1()
Using con As New SQLite.SQLiteConnection(constr)
'con = New SQLite.SQLiteConnection(constr)
con.Open()
Dim str As String = "select * from Material_type"
da = New SQLite.SQLiteDataAdapter(str, con)
Dim ds As New DataSet
da.Fill(ds, "Tb.Material_Type")
dg1.DataSource = ds.Tables("Tb.Material_Type")
'da.Dispose()
'con.Close()
End Using
End Sub
Private Sub F_Update_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using con As New SQLite.SQLiteConnection(constr)
' con = New SQLite.SQLiteConnection(constr)
con.Open()
'MsgBox("OK")
'Calling the function Load form
loadDatadg1()
End Using
End Sub
another part :
Private Sub B_login_Click(sender As Object, e As EventArgs) Handles B_login.Click
Dim connectionString As String = "Data source =Database1.db"
Dim mSQL As String = "select User_Name,User_Password from User where (User_ID = 1 and User_Name = '" & T_User_Name.Text & "' and User_Password = '" & T_User_Password.Text & "')"
Dim dt As DataTable = Nothing
Dim ds As DataSet
Dim rd As SQLiteDataReader
Using con As New SQLiteConnection(connectionString)
Try
con.Open()
Dim cmd As New SQLiteCommand(mSQL, con)
cmd.ExecuteNonQuery()
rd = cmd.ExecuteReader
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
If rd.HasRows Then
F_Update.Show()
Me.Close()
Else
MessageBox.Show("Invalid User Name or Password")
End If
'con.Close()
End Using
End Sub
End Class
can some one help me please ? Thanks in advance
I am trying to set user account for my system. I have two tables (User and Staff)
And this is the interface for setting up user
the name dropdownlist need to be bound to staff table where I can display a list of staff members. When I insert these data to the user table I need to convert the selected staff name into its ID.
I'm really weak in programming and if possible help me with this.
this is the code I am using
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnUserAdd.Click
If ValidData() Then
Try
cmd.Connection = con
con.Open()
sel_id = Convert.ToString(cmbStaffName.SelectedValue)
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "Insert Into dbo.[User] (User_ID,Employee_ID,User_Name,Password,User_Level) values ('" & txtBoxUserID.Text & "','" & sel_id & "','" & txtBoxUserName.Text & "', '" & txtBoxPassword.Text & "','" & ComboBox1.Text & "')"
cmd.ExecuteNonQuery()
MsgBox("Succesfully Added", MsgBoxStyle.Information, "add")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
con.Close()
End If
If Not ValidData() Then
Exit Sub
End If
End Sub
Private Sub btnUserUpdate_Click(sender As Object, e As EventArgs) Handles btnUserUpdate.Click
End Sub
Private Sub Setup_User_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MyHotelManagementSystemDataSet19.Staff' table. You can move, or remove it, as needed.
Me.StaffTableAdapter1.Fill(Me.MyHotelManagementSystemDataSet19.Staff)
'TODO: This line of code loads data into the 'MyHotelManagementSystemDataSet18.Staff' table. You can move, or remove it, as needed.
Me.User_TypeTableAdapter.Fill(Me.MyHotelManagementSystemDataSet17.User_Type)
End Sub
Private Sub cmbStaffName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbStaffName.SelectedIndexChanged
Try
con.Open()
ds = New DataSet()
cmd = New SqlCommand("select * from Staff", con)
Adapter = New SqlDataAdapter(cmd)
adapter.Fill(ds)
cmbStaffName.DataSource = StaffBindingSource1
cmbStaffName.DisplayMember = "Name"
cmbStaffName.ValueMember = "Employee_ID"
Catch ex As Exception
Finally
con.Close()
End Try
End Sub
Private Sub cmbStaffName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbStaffName.SelectedIndexChanged
Try
con.Open()
ds = New DataSet()
cmd = New SqlCommand("select * from Staff", con)
Using adapter as New SqlDataAdapter(cmd)
adapter.Fill(ds)
End Using
cmbStaffName.DisplayMember = "Name"
cmbStaffName.ValueMember = "Employee_ID"
cmbStaffName.DataSource = ds
Catch ex As Exception
Finally
con.Close()
End Try
End Sub