I have accessed a database in VB.NET using the following code:
Public Class Form1
Private Sub btnLoad_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnLoad.Click
Dim con As OleDb.OleDbConnection = New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = AddressBook.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM tblContacts"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Address Book")
MsgBox("Database Open")
con.Close()
MsgBox("Database Closed")
txtFirstName.Text = ds.Tables("AddressBook").Rows(0).Item(1)
txtSurname.Text = ds.Tables("AddressBook").Rows(0).Item(2)
End Sub
End Class
However in line "txtFirstName.Text = ds.Tables("AddressBook").Rows(0).Item(1)", it gives me an exception saying that an instance of an object should be created. I am not understanding what exactly the problem is. How can I create an instance, and of WHAT should I create an instance?
You used a space in
da.Fill(ds, "Address Book")
But no space in
txtFirstName.Text = ds.Tables("AddressBook").Rows(0).Item(1)
For the name of the table. Therefore a table with name "AddressBook" does not exist.
Related
I'm trying to search a date using DateTimePicker in an Access database and have the results show in the DataGridView but it doesn't work. No errors but it just doesn't show the database/results. Here's pictures of the database and the debugged form when it doesn't work in case they are of any use:
and here's my code:
Imports System.Data.OleDb
Public Class Form10
Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Daily Sales.accdb;")
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
Dim dt1 As DateTime = DateTime.Parse(DateTimePicker1.Value)
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Table1] where [TDateField] = #" & dt1.ToString("MM/dd/yyyy"), connection)
Dim da As New OleDbDataAdapter
da.SelectCommand = cmd
DataGridView2.DataSource = da
connection.Close()
End Sub
Private Sub Form10_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "MM/dd/yyyy"
End Sub
End Class
Use the true date value of the datetime picker:
Dim dt1 As DateTime = DateTimePicker1.Value
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Table1] where [TDateField] = #" & dt1.ToString("yyyy'/'MM'/'dd") & "#", connection)
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.
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 have a form with a datagridview (ViewCustomersForm) and a save button.
What I am trying to do is get the user to edit the infotmation in the datagrid view and then hit a save button, which will save the values back to my SQL table.
Unfortunately though, when my save button is pressed I get the following error.
"Value cannot be null."
Pointing at this line of code:
dataadapter.Update(ds.Tables("Customers_table"))
In the context of the below code:
Private Sub ViewCustomersForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Customers._Customers' table. You can move, or remove it, as needed.
Dim connStr As String = "server=barry-laptop\SQLEXPRESS; database=BillingReferenceData; integrated security=yes"
Dim sql As String = "SELECT * FROM Customers"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(sql, conn)
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Dim ds As DataSet = New DataSet()
'---open the connection and fill the dataset---
conn.Open()
dataadapter.Fill(ds, "Customers_table")
conn.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers_table"
End Sub
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connStr As String = "server=barry-laptop\SQLEXPRESS; database=BillingReferenceData; integrated security=yes"
Dim sql As String = "SELECT * FROM Customers"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(sql, conn)
Dim ds As DataSet = New DataSet()
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Dim sqlCmdBuilder As New SqlCommandBuilder(dataadapter)
sqlCmdBuilder.GetUpdateCommand()
dataadapter.Update(ds.Tables("Customers_table"))
End Sub
I am relatively new to VB, so any help or pointers greatly appreciated.
Thanks
I needed to have by variables defined at the Class level, not with in the Subs.
Here is the working code.
Imports System.Data.SqlClient
Imports System.Data.Common
Public Class ViewCustomersForm
Dim ds As DataSet = New DataSet()
Dim connStr As String = "server=barry-laptop\SQLEXPRESS; database=BillingReferenceData; integrated security=yes"
Dim sql As String = "SELECT * FROM Customers"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(Sql, conn)
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Private Sub Button1_Click(sender As Object, e As EventArgs)
End Sub
Private Sub ViewCustomersForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'---open the connection and fill the dataset---
conn.Open()
dataadapter.Fill(ds, "Customers_table")
conn.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers_table"
End Sub
Private Sub Button_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim sqlCmdBuilder As New SqlCommandBuilder(dataadapter)
sqlCmdBuilder.GetUpdateCommand()
dataadapter.Update(ds.Tables("Customers_table"))
End Sub
End Class
Trying to get this bit of code to enter a player name fill it in the datarow then update it in the DB. It currentley updates in the datarow but I can not get the code right to update the DB. Could you please help cheers.
Using da As OleDbDataAdapter = New OleDbDataAdapter("SELECT * FROM Team1", con)
da.Fill(ds, "BPAWA")
txtFirstName.Text = ds.Tables("BPAWA").Rows(0).Item(1)
T1P1 = InputBox("Name of Player 1")
ds.Tables("BPAWA").Rows(0).Item(1) = T1P1
ds.Tables("BPAWA").AcceptChanges()
ds.AcceptChanges()
da.Update(ds, "BPAWA")
MsgBox("Player 1 Added Successfully")
End Using
You OleDbDataAdapter is not linked to an actual command neither you seem to have created the adapter in your code. See an example here
Missing a line like this
Dim da As OleDbDataAdapter = new OleDbDataAdapter(selectCommand, connection);
so I could rewrite your code in this way (Avoiding the global variables)
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
Dim dbProvider As String = "PROVIDER=microsoft.ace.oledb.12.0;"
Dim dbSource As String = "Data Source = C:\BP_Table_Project.accdb"
Dim ds as DataSet = new DataSet()
Using con As OleDbConnection = new OleDbConnection()
con.ConnectionString = dbProvider & dbSource
con.Open()
MsgBox("Connection With Database Established", 0, "Database Connection")
Using da as OleDbDataAdapter = new OleDbDataAdapter("SELECT * FROM Team1", con)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(da)
da.Fill(ds, "BPAWA")
......
da.Update(ds, "BPAWA")
MsgBox("Player 1 Added Successfully")
End Using
MsgBox("Connection With Database Closed", 0, "Database Connection")
End Using
End Sub
Before da.Update(ds, "BPAWA")
Add:
ds.Tables("BPAWA").AcceptChanges()
ds.AcceptChanges()