Invalid object name space - vb.net

I made a table in SQLServer and the idea of code is to fill the blank and click Insert and a new user will be added to database and the DataGridView, but I got this error:
Invalid object name 'Users'.
This error appear after I click the Insert button:
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim connection As New SqlConnection("Data Source=LAPTOP-DLGJAU3D;Initial Catalog=master;Integrated Security=True")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
EmployeeListDataGridView.DataSource = GetEmployeeList()
End Sub
Private Function GetEmployeeList() As DataTable
Dim dtEmployees As New DataTable
Dim connString As String = ConfigurationManager.ConnectionStrings("dbx").ConnectionString
Using conn As New SqlConnection(connString)
Using cmd As New SqlCommand("SELECT * FROM dbo.EMPLOYEES", conn)
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
dtEmployees.Load(reader)
End Using
End Using
Return dtEmployees
End Function
Private Sub BTN_INSERT_Click(sender As Object, e As EventArgs) Handles BTN_INSERT.Click
Dim command As New SqlCommand("insert into Users(Fname, Lname, age) values('" & TextBoxFN.Text & "','" & TextBoxLN.Text & "'," & TextBoxAGE.Text & ")", connection)
connection.open()
If command.ExecuteNonQuery() = 1 Then
MessageBox.Show("New User Added")
Else
MessageBox.Show("User Not Added")
End If
connection.close()
End Sub
End Class

Related

Vb.net cant save picture using the ms.access Database

Okay please forgive me if this sound annoying but i keep getting an error nullreference whenever im trying to input my data.. Im sorry if im doing this wrong This is my first time posting here :
Imports System.IO
Imports System.Data.OleDb
Public Class halaman_daftar_anggota
Dim Conn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim CMD As OleDbCommand
Dim bytimage As Byte()
Dim LokasiDB As String
Sub Koneksi()
LokasiDB = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=perpustakaan.accdb"
Conn = New OleDbConnection(LokasiDB)
If Conn.State = ConnectionState.Closed Then Conn.Open()
End Sub
Private Sub halaman_daftar_anggota_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Koneksi()
da = New OleDbDataAdapter("Select * from data_anggota", Conn)
ds = New DataSet
ds.Clear()
da.Fill(ds, "data_anggota")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim dialog As OpenFileDialog = New OpenFileDialog()
dialog.Title = "Browse Foto"
dialog.Filter = "image files(*.png; *.bmp; *.jpg;*.jpeg; *.gif; |*.png; *.bmp; *.jpg;*.jpeg; *.gif;)"
If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
PictureBox1.Image = Image.FromFile(dialog.FileName)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim ms As New System.IO.MemoryStream
Dim bmpimage As New Bitmap(PictureBox1.Image)
bmpimage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
bytimage = ms.ToArray()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Call Koneksi()
Dim simpan As String = "INSERT INTO data_buku (nomor_induk,nama_siswa,kelas_siswa,foto) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "',#image)"
CMD.Parameters.AddWithValue("#image", bytimage) <-"Error object reference not set to an instance of an object"
CMD = New OleDbCommand(simpan, Conn)
CMD.ExecuteNonQuery()
MsgBox("Berhasil")
End Sub
End Class
Whenever im trying to save a picture.in my database j already set foto as ole object... Im sorry..

Update statement in sql doesnt work , microsoft access with vb.net

I currently doing the changepassword function in my vb.net project, user can click change password to change their password
But my code doesnt update correctly , it will show "updated" but when i go to my database access table the data still remain the same
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.IO
Public Class frmUserDetail
Dim ds As New DataSet
Dim dt As New DataTable
Dim cmd As SqlCommand
Dim con As SqlConnection
Dim da As New OleDbDataAdapter
Dim conn As New OleDbConnection
Private Sub FrmUserDetail_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\phoneOnline.accdb;Persist Security Info=false;")
loadUserDetail()
txtUserName.Enabled = False ' set it to false so user cannot do shit with it
End Sub
Public Sub loadUserDetail()
conn.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\phoneOnline.accdb;Persist Security Info=false;")
Dim cmd As OleDbCommand
Dim userName As String = frmMain.lblUserLogin.Text
'specify name of the user
Dim search As String = "SELECT * from tblUser WHERE UserName= '" + userName + "'"
cmd = New OleDbCommand(search)
cmd.Connection = conn
Dim dtt As New DataTable()
Dim daa As New OleDbDataAdapter(cmd)
daa.Fill(dtt)
If dtt.Rows.Count() > 0 Then
txtUserName.Text = dtt.Rows(0)(0).ToString 'show the userName
txtUserPassword.Text = dtt.Rows(0)(1).ToString 'show the password of the user
txtEmail.Text = (dtt.Rows(0)(2).ToString) 'show user email
Else
MsgBox("You are currently login as a guest")
End If
End Sub
Private Sub changePassword()
If cbChangePassword.Checked Then
txtChangePassword.Enabled = True
Else
txtChangePassword.Enabled = Not (True)
End If
End Sub
Private Sub CbChangePassword_CheckedChanged(sender As Object, e As EventArgs) Handles cbChangePassword.CheckedChanged
changePassword()
End Sub
Private Sub BtnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
conn.Open()
Dim cmd As OleDbCommand
Dim sql As String = "UPDATE tblUser SET UserPassword=#userpass,Email=#email WHERE UserName=#userName;"
cmd = New OleDbCommand(sql.ToString, conn)
cmd.Parameters.AddWithValue("#username", txtUserName.Text)
cmd.Parameters.AddWithValue("#userpass", txtChangePassword.Text)
cmd.Parameters.AddWithValue("#email", txtEmail.Text) 'pass the time variable from the form 1 to the parameter
cmd.ExecuteNonQuery()
MsgBox("updated")
conn.Close()
End Sub
Private Sub BtnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Hide()
frmMain.Show()
End Sub
End Class
I Expect my database will get updated when i updated it

how to insert checked items from checkedlistbox to SQL database?

I am trying to save checked items from a checkedlistbox to my SQL database and i am filling my checkedlistbox from the same SQL database,So far i am able to get the text of checked item from the checkedlistbox and i saved it in a string then i used a label to display if i am getting the text of checked item or not and its working but when i try to insert the checked data in database i get a error "Connection property has not been initialized." on ExecuteNonQuery() method.
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim da As New SqlDataAdapter
Dim dt As New DataTable
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.ConnectionString = connectionString
conn.Open()
Dim str As String
str = "Select sem1 From sem"
da = New SqlDataAdapter(str, conn)
dt = New DataTable
da.Fill(dt)
CheckedListBox1.DataSource = dt
CheckedListBox1.DisplayMember = "sem1"
conn.Close()
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String
Dim cmd As New SqlCommand
Dim sql As String
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim itemChecked As Object
For Each itemChecked In CheckedListBox1.CheckedItems
str = itemChecked.item("sem1").ToString
Label1.Text = str
sql = "insert into pretab(pre) values('" + str + "')"
cmd.ExecuteNonQuery()
Next
conn.Close()
End Using
End Sub
End Class
This error
The problem maybe arised from your query syntax. Try this:
sql = "insert into pretab(pre) values(#str)"
cmd.Parameters.AddWithValue("#str", str)
cmd.ExecuteNonQuery()
OOPS.. I just realised that you forgot to assign your command with connection. So, please try to add the following statement:
cmd = New SqlCommand(sql, conn)
befor execution your command. So the final code should look like this:
sql = "insert into pretab(pre) values(#str)"
cmd = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#str", str)
cmd.ExecuteNonQuery()
First off I would do data operations in a class e.g. (note I focus on inserts). You need to change server and catalog to your server and catalog on SQL-Server.
Imports System.Data.SqlClient
Public Class Operations
Private Server As String = "KARENS-PC"
Private Catalog As String = "CheckedListBoxDatabase"
Private ConnectionString As String = ""
Public Sub New()
ConnectionString = $"Data Source={Server};Initial Catalog={Catalog};Integrated Security=True"
End Sub
Public Function Read() As DataTable
' read rows for checked listbox here
End Function
Public Sub Insert(ByVal sender As List(Of String))
Using cn As SqlConnection = New SqlConnection With {.ConnectionString = ConnectionString}
Using cmd As SqlCommand = New SqlCommand With {.Connection = cn, .CommandText = "insert into pretab(pre) values (#pre)"}
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#pre", .SqlDbType = SqlDbType.NVarChar})
cn.Open()
For Each item In sender
cmd.Parameters("#pre").Value = item
cmd.ExecuteNonQuery()
Next
End Using
End Using
End Sub
End Class
Form code
Public Class Form1
Private ops As New Operations
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Result = CheckedListBox1.Items.OfType(Of String).Where(Function(item, index) CheckedListBox1.GetItemChecked(index)).ToList
ops.Insert(Result)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckedListBox1.DataSource = ops.Read
CheckedListBox1.DisplayMember = "sem1"
End Sub
End Class
It appears that you did not provide the connection to the command. Your code was button click
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String
Dim cmd As New SqlCommand
Dim sql As String
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim itemChecked As Object
For Each itemChecked In CheckedListBox1.CheckedItems
str = itemChecked.item("sem1").ToString
Label1.Text = str
sql = "insert into pretab(pre) values('" + str + "')"
cmd.ExecuteNonQuery()
Next
conn.Close()
End Using
End Sub
What you need to do is before cmd.ExecuteNonQuery() you need to provide it a connection cmd.connection = connectionString
this will remove the cmd.ExecuteNonQuery() error.

how to make a ComboBox predictive (AutoSelective) in Vb.net [duplicate]

This question already has answers here:
VB.net ComboBox auto drop down on input
(2 answers)
Closed 6 years ago.
I am populating the items of ComboBox from Database. Now I want to give Combobox a functionality such that, as soon as user type few letters or a word, it automatically selects and displays the item containing those alphabets or words. Presently I have written following lines of code
Private Sub From1_Load(By val connection = New OledbConnection("Data Source")
con.Open()
cmd = New OledbCommand("SQL",con)
DataReader = cmd.ExecuteReader
While DataReader.Read
ComboBox1.items.Add(DataReader(0))
End While
Con.Close()
Set the following properties of the ComboBox before filling
ComboBox1.AutoCompleteSource = AutoCompleteSource.ListItems
ComboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend
Imports System.Data.OleDb
Public Class Form1
Dim conn As New OleDbConnection
Dim reader1 As OleDbDataReader
Dim strSQL As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.connect()
Me.fillcombo()
End Sub
Sub connect()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Nick\Desktop\aswer\aswer\databee.accdb"
conn.Open()
End Sub
Sub fillcombo()
strSQL = "select * from Table1"
Dim cmd As New OleDb.OleDbCommand
cmd.CommandText = strSQL
cmd.Connection = conn
reader1 = cmd.ExecuteReader
While (reader1.Read())
ComboBox1.Items.Add(reader1("ID Number"))
End While
cmd.Dispose()
reader1.Close()
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
strSQL = "select * from Table1 where id='" & ComboBox1.Text & "'"
Dim comnd As New OleDb.OleDbCommand
comnd.CommandText = strSQL
comnd.Connection = conn
reader1 = comnd.ExecuteReader
If (reader1.Read() = True) Then
TextBox1.Text = (reader1("Name"))
End If
comnd.Dispose()
reader1.Close()
End Sub
End Class

create table in access database using Adox in vb

I'm using a Windows form application in Visual Basic 2012 to create a new Microsoft Access database using .ADOX. I can create the database but can't create a table in the database.
My code is :
Imports ADOX
Imports System.Data.OleDb
Public Class Form1
Dim mycommand As OleDbCommand
Dim myconnection As OleDbConnection
Dim myReader As OleDbDataReader
Dim str As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cat As New Catalog()
Dim tablename As String = "Users"
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb;Jet OLEDB:Engine Type=5")
cat = Nothing
myconnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb ")
myconnection.Open()
str = "CREATE TABLE [ " & tablename & "] ([Username] varchar(50)), ([Password] varchar(50)), ([E-mail] varchar(75))"
mycommand = New OleDb.OleDbCommand(str, myconnection)
mycommand.ExecuteNonQuery()
MsgBox("Database created")
End Sub
End Class
The error is get is:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in CREATE TABLE statement.
Any help is appreciated.
EDITED:
The following code gets past the first error but i now get a field definition error, i know the code should work as it works with adding a number field, possible because the field type in access is short text and long text but anything i've tried doesn't seem to work.
Imports ADOX
Imports System.Data.OleDb
Public Class Form1
Dim mycommand As OleDbCommand
Dim myconnection As OleDbConnection
Dim myReader As OleDbDataReader
Dim str As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cat As New Catalog()
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb;Jet OLEDB:Engine Type=5")
cat = Nothing
myconnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb ")
myconnection.Open()
str = "CREATE TABLE [Users] (Username Varchar(50), Password Varchar(50), E-mail Varchar(50))"
mycommand = New OleDb.OleDbCommand(str, myconnection)
mycommand.ExecuteNonQuery()
MsgBox("Database created")
End Sub
End Class
Looks like you have too many parenthesizes, but I think the actual error is coming from the leading space you have in your query:
V
str = "CREATE TABLE [ " & tablename & "]
Try changing it to:
str = "CREATE TABLE [" & tablename & "] ([Username] varchar(50), [Password] varchar(50), [E-mail] varchar(75))"
Make sure you dispose of your objects, preferably in a using block:
Example:
Using cn As New OleDb.OleDbConnection(mdb)
cn.Open()
Using cmd As New OleDb.OleDbCommand(str, cn)
cmd.ExecuteNonQuery()
End Using
End Using
At the end the code looks like this:
Imports ADOX
Imports System.Data.OleDb
Public Class Form1
Dim mycommand As OleDbCommand
Dim myconnection As OleDbConnection
Dim myReader As OleDbDataReader
Dim str As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cat As New Catalog()
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Test\DDL.mdb;Jet OLEDB:Engine Type=5")
cat = Nothing
Using myconnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Test\DDL.mdb ")
myconnection.Open()
str = "CREATE TABLE [Users] ([Username] varchar(50), [Password] varchar(50), [E-mail] varchar(50))"
Using mycommand As New OleDb.OleDbCommand(str, myconnection)
mycommand.ExecuteNonQuery()
End Using
End Using
MsgBox("Database created")
End Sub
End Class