Changing DataGridview after filter combobox - vb.net

I'm trying to refill my DataGridView after a filter selection in a combobox.
Here is my code where I try...at this moment the code is clearing the DataGridview and just fill only on row with only 1 cell..KlantID = 7
Any idea?
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
klantid = ComboBox1.SelectedValue
Dim myConnection As OleDbConnection
Dim DBpath As String = "C:\Facturatie\CharelIjs.accdb"
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBpath & ";Persist Security Info=True"
myConnection = New OleDbConnection(sConnectionString)
myConnection.Open()
Dim SQLstr As String
SQLstr = "SELECT * FROM tblKlant WHERE KlantID = #klantid"
Dim cmd As New OleDbCommand(SQLstr, myConnection)
Dim da As New OleDbDataAdapter(cmd)
Dim ds As New DataSet()
cmd.Parameters.Add("#klantid", OleDbType.VarChar)
cmd.Parameters(0).Value = klantid
Try
da.Fill(ds, "tblKlant")
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Can't load Web page" & vbCrLf & ex.Message)
Return
End Try
DataGridView1.DataSource = ds
DataGridView1.DataMember = "tblKlant"
DataGridView1.Refresh()
End Sub

Why are you populating records on every combobox_SelectionChange event execution. Try to filter your data only instead of query execution.
And, better to use SelectedValueChanged event instead of SelectionChange.
Private Sub form_Load(sender As Object, e As EventArgs) Handles Me.Load
//Fill your data here with DataView
Dim myConnection As OleDbConnection
Dim DBpath As String = "C:\Facturatie\CharelIjs.accdb"
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBpath & ";Persist Security Info=True"
myConnection = New OleDbConnection(sConnectionString)
myConnection.Open()
Dim cmd As New OleDbCommand("SELECT * FROM tblKlant", myConnection)
Dim da As New OleDbDataAdapter(cmd)
Dim dt As New DataTable() 'Dont use dataset if your are not relating more than one tables
cmd.Parameters.Add("#klantid", OleDbType.VarChar)
cmd.Parameters(0).Value = klantid
Try
da.Fill(dt)
dt.TableName = "tblKlant"
cmd.ExecuteNonQuery()
DataGridView1.DataSource = dt.DefaultView
DataGridView1.DataMember = "tblKlant"
Catch ex As Exception
MsgBox("Can't load Web page" & vbCrLf & ex.Message)
Return
End Try
End Sub
Private Sub combobox_SelectedValueChanged(sender As Object, e As EventArgs) Handles combobox.SelectedValueChanged
IF combobox.SelectedValue IsNot Nothing Then
Dim dv As DataView = DirectCast(DataGridView1.DataSource, DataView)
dv.RowFilter = "KlantID=" + combobox.SelectedValue.ToString()
Else
dv.RowFilter = vbNullString
End IF
End Sub

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..

Adapter update statement in oledb

I have a form with retrieved data form ms access database. While updating using the adapter update statement, it shows Syntax error.
The following are the connection code in form load event and update button click event.
could you please let me know whats wrong in this?
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Dim Con As New OleDbConnection()
Dim Cmd As New OleDbCommand
Dim SQL As String = "SELECT * FROM Heidelberg"
Con.ConnectionString = strConn
Try
Con.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Cmd = New OleDbCommand(SQL, Con)
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
ds = New DataSet
Adapter.Fill(ds, "testing")
MaxRows = ds.Tables("testing").Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
Dim cb As New OleDb.OleDbCommandBuilder(Adapter)
ds.Tables("testing").Rows(inc).Item(5) = TextBox1.Text
ds.Tables("testing").Rows(inc).Item(2) = TextBox2.Text
ds.Tables("testing").Rows(inc).Item(3) = TextBox3.Text
ds.Tables("testing").Rows(inc).Item(4) = TextBox4.Text
Try
Adapter.Update(ds, "testing")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
You have way too many commands in your Form.Load.
One
Dim Cmd As New OleDbCommand
Two
Cmd = New OleDbCommand(SQL, Con)
Three
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
Every time you use the New keyword, you create another command.
If you are only dealing with a single table, you don't need a DataSet. The extra object adds extra weight and complicates the code a bit.
Private inc As Integer
Private Adapter As New OleDbDataAdapter
Private MaxRows As Integer
Private dat As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Using Con As New OleDbConnection(strConn)
Using Cmd As New OleDbCommand("SELECT * FROM Heidelberg;", Con)
Adapter.SelectCommand = Cmd
Try
Adapter.Fill(dat)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Using
MaxRows = dat.Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
dat.Rows(inc).Item(5) = TextBox1.Text
dat.Rows(inc).Item(2) = TextBox2.Text
dat.Rows(inc).Item(3) = TextBox3.Text
dat.Rows(inc).Item(4) = TextBox4.Text
Dim cb As New OleDbCommandBuilder(Adapter)
'This will take care of any spaces that you have in column names.
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
Try
Adapter.Update(dat)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

It gives value in textbox but only after finishing it . how to display data while running timer?

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Me.TextBox1.Text = "hello"
Dim connectionString As String = "Data Source=192.168.0.199;Initial Catalog=NEWDATABASE;Persist Security Info=True;User ID=admin;Password=123456"
Dim connection As New SqlConnection(connectionString)
connection.Open()
Dim sql As String = "SELECT TOP (" & topvalue & ") * FROM [NEWDATABASE].[dbo].[MachineParameter] WHERE status = '0' ORDER BY Id ASC"
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
dataadapter.Fill(ds, "table")
DataGridViewtx.DataSource = ds
DataGridViewtx.DataMember = "table"
connection.close()
end sub

Register Form Issues VB.Net

I am having an issue when I am setting up this Register form.
My current code is this:
Public Class Form2
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim MyDocumentsFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim DBTest1 As String
Dim DBTestP1 As String
Dim cmd As New OleDbCommand(sql, con)
Dim connStr As String
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New OleDb.OleDbConnection(connStr)
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
TheDatabase = "\Robocopy_Test.accdb"
MyDocumentsFolder = "C:\Users\Dan\Desktop\WindowsApplication2"
FullDatabasePath = MyDocumentsFolder & TheDatabase
dbSource = "Data Source = C:\Users\Dan\Desktop\WindowsApplication2\Robocopy_Testaccdb1.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM Robocopy"
da = New OleDb.OleDbDataAdapter(sql, con)
'da.Fill(ds, "Robocopy")
MessageBox.Show("Databse is Open")
DBTest1 = DBTest.Text
DBTestP1 = DBTestP.Text
'DBTest.Text = ds.Tables("Robocopy").Rows(0).Item(1)
'DBTestP.Text = ds.Tables("Robocopy").Rows(0).Item(2
sql = "INSERT INTO Robocopy(username,password) VALUES('" & DBTest1 & "','" & DBTestP1 & "')"
cmd.Connection = connection
connection.Open()
cmd.CommandText = sql
da.InsertCommand = cmd
da.InsertCommand.ExecuteNonQuery()
connection.Close()
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Sub
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
con.Close()
MessageBox.Show("Database Is now Closed")
End Sub
End Class
I am having the issue at connection.open(). The error that I am having is
The ConnectionString property has not been initialized.
I have been trying for the past hour to find different ways to write to the database but to no prevail and I cannot figure this out.
[In response to Steve
My code after editing and still the same error
Imports System.Data.OleDb
Public Class Form2
Dim connection As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim MyDocumentsFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim DBTest1 As String
Dim DBTestP1 As String
Dim cmd As New OleDbCommand(sql, connection)
Dim connStr As String
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New OleDb.OleDbConnection(connStr)
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
TheDatabase = "\Robocopy_Test.accdb"
MyDocumentsFolder = "C:\Users\Dan\Desktop\WindowsApplication2"
FullDatabasePath = MyDocumentsFolder & TheDatabase
dbSource = "Data Source = C:\Users\Dan\Desktop\WindowsApplication2\Robocopy_Testaccdb1.accdb"
Me.connection.ConnectionString = dbProvider & dbSource
Me.connection.Open()
sql = "SELECT * FROM Robocopy"
da = New OleDb.OleDbDataAdapter(sql, connection)
'da.Fill(ds, "Robocopy")
MessageBox.Show("Databse is Open")
DBTest1 = DBTest.Text
DBTestP1 = DBTestP.Text
'DBTest.Text = ds.Tables("Robocopy").Rows(0).Item(1)
'DBTestP.Text = ds.Tables("Robocopy").Rows(0).Item(2
sql = "INSERT INTO Robocopy(username,password) VALUES('" & DBTest1 & "','" & DBTestP1 & "')"
cmd.Connection = connection
connection.Open()
cmd.CommandText = sql
da.InsertCommand = cmd
da.InsertCommand.ExecuteNonQuery()
connection.Close()
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Sub
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
connection.Close()
MessageBox.Show("Database Is now Closed")
End Sub
End Class
Global variables could be very ....evil. Expecially if you name them with the same name of a local variable.
Me.connection is not the same variable connection declared as local variable inside the sub. You set the connection string on the global variable then use the local variable without any connection string
Change these two lines
Me.connection.ConnectionString = dbProvider & dbSource
Me.connection.Open()
removing the Me.
connection.ConnectionString = dbProvider & dbSource
connection.Open()
and don't open the connection two times.
In any case, you don't need the adapter at all to execute an insert command
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Dan\Desktop\WindowsApplication2\Robocopy_Testaccdb1.accdb"
Dim connStr = dbProvider & dbSource
DBTest1 = DBTest.Text
DBTestP1 = DBTestP.Text
sql = "INSERT INTO Robocopy(username,[password]) VALUES('" & DBTest1 & "','" & DBTestP1 & "')"
Using connection = New OleDb.OleDbConnection(connStr)
Using cmd = new OleDb.OleDbCommand(sql, connection )
connection.Open()
cmd.ExecuteNonQuery()
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Using
End Using
End Sub
I see also that you have commented out the Parameterized approach to your query. Please do yourself a favour and restore as soon as possible the parameters logic. It is a lot more safe and avoids numerous errors
Finally Password is a reserved keyword in Access.Use square brakets around it otherwise you will see an unexplicable "Syntax Error" in your insert command

Bind Data From Microsoft Acess to Textbox

I have a database named PriceTesting ( using Microsoft Access 2007 ) that contains a table named tbl_dress with columns:
Dress_ID, Dress_Name, Dress_Price
In the form, I have created a combobox and a text box.
So far I've succeeded binding the combobox with Dress_Name data using this code :-
Private Sub FillCombo()
Try
Dim fillcon As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\annonymous\Documents\Visual Studio 2012\Projects\DressTest\DressTest\db\PriceTesting.accdb")
Dim query As String = ("SELECT Dress_Name FROM tbl_dress")
Dim da As New OleDb.OleDbDataAdapter(query, fillcon)
Dim ds As New DataSet
da.Fill(ds)
ComboBox1.ValueMember = "Dress_Name"
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.SelectedIndex = 0
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try
End Sub
and it works... everytime the form loads, the combobox contains the data from Dress_Name column.
Now I want the texbox.text = Dress_Price WHERE Dress_Name = combox.selecteditem
any idea how to do that?
what I have in mind is only this : -
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
query = " SELECT Dress_Price FROM tbl_dress WHERE Dress_Name = ' " & Combobox1.Text & " ' "
Textbox1.text = query
End Sub
TRY THIS and be sure to add Dress_Price"in your query
Private Sub FillCombo()
Try
Dim fillcon As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\annonymous\Documents\Visual Studio 2012\Projects\DressTest\DressTest\db\PriceTesting.accdb")
Dim query As String = ("SELECT Dress_Name, Dress_Price FROM tbl_dress")
Dim da As New OleDb.OleDbDataAdapter(query, fillcon)
Dim ds As New DataSet
da.Fill(ds)
ComboBox1.ValueMember = "Dress_Name"
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.SelectedIndex = 0
texbox.DataBindings.Clear()
texbox.DataBindings.Add("Text", ds.Tables(0), "Dress_Price")
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try
End Sub
OR just change the code in your idea like this and be sure to add Dress_Price"in your query
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
dim dt as DataTable = Combobox1.DataSource
dim dr as DataRow = dt.Rows(Combobox1.SelectedIndex)
Textbox1.text = iif(dr.isNull("Dress_Price"), "", dr.isNull("Dress_Price").Tostring)
End Sub
Dim fillcon As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\annonymous\Documents\Visual Studio 2012\Projects\DressTest\DressTest\db\PriceTesting.accdb")
Dim query As String = " SELECT Dress_Price FROM tbl_dress WHERE Dress_Name = ' " & Combobox1.Text & "'"
Dim da As New OleDb.OleDbDataAdapter(query, fillcon)
Dim dt As New DataTable
da.Fill(dt)
Textbox1.text = dt.rows(0).item(0)
Search for parameters to avoid sql injection. Also try to improve the query and use the ID instead of the dress_name