Search Data in Multiple Table and Found Result in Multiple GridView .VB - vb.net

Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class search
Dim conn As New SqlConnection
Dim da As New SqlDataAdapter
Dim strcon As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Application\Abhi\Software\Software\Vansh.mdf;Integrated Security=True;User Instance=True"
Private Sub search_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
' con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Application\Abhi\Software\Software\Vansh.mdf;Integrated Security=True;User Instance=True"
conn = New SqlConnection(strcon)
conn.Open()
loaddata()
' txtsearch.Enabled = False
' txtsearch.Text = "Student Id is auto number"
End Sub
Public Sub loaddata()
conn = New SqlConnection(strcon)
conn.Open()
Dim str As String = "Select * From Payment "
da = New SqlDataAdapter(str, conn)
Dim ds As New DataSet
da.Fill(ds, "Payment")
DataGridView1.DataSource = ds.Tables("Payment")
da.Dispose()
conn.Close()
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
For Each txt In {txtmo, txtsearch}
txt.Clear()
Next
End Sub
Private Sub Button1_Click_1(sender As System.Object, e As System.EventArgs)
End Sub
Private Sub btnhome_Click(sender As System.Object, e As System.EventArgs) Handles btnhome.Click
Me.Hide()
Dim rd As New Home_Page
rd.Show()
End Sub
Private Sub txtsearch_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtsearch.TextChanged
Try
conn = New SqlConnection(strcon)
conn.Open()
If txtsearch.Text = " " Then
loaddata()
Else
conn = New SqlConnection(strcon)
conn.Open()
Dim Str As String = "Select Date, Name, Amount from Payment where Name like '" + txtsearch.Text + "%' "
da = New SqlDataAdapter(Str, conn)
Dim ds As New DataSet
da.Fill(ds, "Payment")
DataGridView1.DataSource = ds.Tables("Payment")
da.Dispose()
conn.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub DataGridView1_CellContentClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
Private Sub txtmo_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtmo.TextChanged
Try
conn = New SqlConnection(strcon)
conn.Open()
If txtsearch.Text = " " Then
loaddata()
Else
conn = New SqlConnection(strcon)
conn.Open()
Dim Str As String = "Select Date, Name, Amount from Payment where Date like '" + txtmo.Text + "%' "
da = New SqlDataAdapter(Str, conn)
Dim ds As New DataSet
da.Fill(ds, "Payment")
DataGridView1.DataSource = ds.Tables("Payment")
da.Dispose()
conn.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub DateTimePicker1_ValueChanged(sender As System.Object, e As System.EventArgs) Handles DateTimePicker1.ValueChanged
Try
conn = New SqlConnection(strcon)
conn.Open()
If txtsearch.Text = " " Then
loaddata()
Else
conn = New SqlConnection(strcon)
conn.Open()
Dim Str As String = "Select Date, Name, Amount from Payment where Date like '" + DateTimePicker1.Text + "%' "
da = New SqlDataAdapter(Str, conn)
Dim ds As New DataSet
da.Fill(ds, "Payment")
DataGridView1.DataSource = ds.Tables("Payment")
da.Dispose()
conn.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub DataGridView2_CellContentClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView2.CellContentClick
End Sub
End Class

Related

DataGridView refreshing fixed position in row filter textbox in vb.net

I want when filtering rows in the textbox then the database is updated from other applications then I do a refresh I want the datagridview that I filter in the textbox in a fixed position and also when selected in the combobox as well. Maybe my code isn't perfect. So there may be the best solution.
Thanks
VIEW DATAGRIDVIEW
Public Class Form1
Dim Path As String = Application.StartupPath()
Dim cn = "provider=Microsoft.Jet.OLEDB.4.0; data source=" & Path & "; Extended Properties=dBase IV"
Private WithEvents dt As New DataTable
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.PopulateComboBox()
Me.PopulateDataGridView()
Me.clearfiltercombobox()
End Sub
Private Sub PopulateDataGridView()
Try
Dim query = "select ITM,ART,QTY FROM EXAMPLE WHERE QTY > 0 AND BRAND = #BRAND"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#BRAND", ComboBox1.SelectedValue)
Using adapter As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
adapter.Fill(dt)
Me.DataGridView1.DataSource = dt
End Using
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Try
CType(DataGridView1.DataSource, DataTable).DefaultView.RowFilter = String.Format("ITM LIKE '%{0}%' OR ITM LIKE '%{0}%'", TextBox1.Text)
Catch ex As Exception
MsgBox("No match found")
End Try
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectionChangeCommitted
Me.TextBox1.Text = ""
Me.PopulateDataGridView()
End Sub
Private Sub PopulateComboBox()
Dim query As String = "SELECT DISTINCT BRAND FROM EXAMPLE WHERE QTY > 0"
Try
Using con As OleDbConnection = New OleDbConnection(cn)
Using sda As OleDbDataAdapter = New OleDbDataAdapter(query, con)
'Fill the DataTable with records from Table.
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
'Insert the Default Item to DataTable.
Dim row As DataRow = dt.NewRow()
row(0) = ""
dt.Rows.InsertAt(row, 0)
'Assign DataTable as DataSource.
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "BRAND"
ComboBox1.ValueMember = "BRAND"
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
Private Sub clearfiltercombobox()
Try
ComboBox1.ResetText()
TextBox1.Text = ""
Dim query = "select ITM,ART,QTY FROM EXAMPLE WHERE QTY > 0"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
Using adapter As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
adapter.Fill(dt)
Me.DataGridView1.DataSource = dt
End Using
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
Private Sub Refreshonly_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Refreshonly.Click
Me.clearfiltercombobox()
DataGridView1.Refresh()
End Sub
Private Sub clearall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Clearall.Click
Me.clearfiltercombobox()
End Sub
End Class

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

Updating MS Access Database through DataGridView in Visual Basic

I'm new to vb.net and I'm trying to update my MS access database from a datagridview in visual basic through a button. Whenever I click on the button to update, I'm getting an error which says "NullReferenceException was unhandled". Please help me. These are my codes:
Imports System.Data.OleDb
Public Class Form1
Public Cnn As New OleDb.OleDbConnection
Public Cmd As New OleDb.OleDbCommand
Public DR As OleDbDataReader
Public DA As OleDbDataAdapter
Public DS As DataSet
Public DT As DataTable
Public cmdBld As OleDbCommandBuilder
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DTBClassRecordsDataSet.tblRecords' table. You can move, or remove it, as needed.
Me.TblRecordsTableAdapter.Fill(Me.DTBClassRecordsDataSet.tblRecords)
dgvRecords.AllowUserToAddRows = True
dgvRecords.AutoGenerateColumns = True
If Cnn.State = ConnectionState.Open Then Cnn.Close()
Cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\JEM FLOR\Projects\CLASS RECORD\DTBClassRecords.accdb"
Cnn.Open()
Cmd.Connection = Cnn
ds.Tables.Add(dt)
DA = New OleDbDataAdapter("Select * from tblRecords", Cnn)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
da.Fill(dt)
dgvRecords.DataSource = dt.DefaultView
DataGridShow()
End Sub
Private Sub DataGridShow()
Cmd = New OleDbCommand("SELECT * FROM tblRecords", Cnn)
Cnn.Open()
DA = New OleDbDataAdapter(Cmd)
cmdBld = New OleDbCommandBuilder(DA)
DS = New DataSet()
DA.Fill(DS, "table1")
dgvRecords.DataSource = DS.Tables("tblRecords").DefaultView
Cnn.Close()
End Sub
Private Sub dgvRecords_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvRecords.CellEndEdit
For Each row As DataGridViewRow In dgvRecords.Rows
On Error Resume Next
If Not row.IsNewRow Then
row.Cells("QR1DataGridViewTextBoxColumn").Value = ((row.Cells("Q1DataGridViewTextBoxColumn").Value / row.Cells("TI1DataGridViewTextBoxColumn").Value) * 50 + 50)
row.Cells("QR2DataGridViewTextBoxColumn").Value = ((row.Cells("Q2DataGridViewTextBoxColumn").Value / row.Cells("TI2DataGridViewTextBoxColumn").Value) * 50 + 50)
row.Cells("QR3DataGridViewTextBoxColumn").Value = ((row.Cells("Q3DataGridViewTextBoxColumn").Value / row.Cells("TI3DataGridViewTextBoxColumn").Value) * 50 + 50)
row.Cells("QR4DataGridViewTextBoxColumn").Value = ((row.Cells("Q4DataGridViewTextBoxColumn").Value / row.Cells("TI4DataGridViewTextBoxColumn").Value) * 50 + 50)
row.Cells("QR5DataGridViewTextBoxColumn").Value = ((row.Cells("Q5DataGridViewTextBoxColumn").Value / row.Cells("TI5DataGridViewTextBoxColumn").Value) * 50 + 50)
End If
Dim qr1 As Integer = row.Cells("QR1DataGridViewTextBoxColumn").Value.ToString
Dim qr2 As Integer = row.Cells("QR2DataGridViewTextBoxColumn").Value.ToString
Dim qr3 As Integer = row.Cells("QR3DataGridViewTextBoxColumn").Value.ToString
Dim qr4 As Integer = row.Cells("QR4DataGridViewTextBoxColumn").Value.ToString
Dim qr5 As Integer = row.Cells("QR5DataGridViewTextBoxColumn").Value.ToString
If Not row.IsNewRow Then
Dim rating As Double = CInt((qr1 + qr2 + qr3 + qr4 + qr5) / 5)
row.Cells("QRDataGridViewTextBoxColumn").Value = rating
End If
Next
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim sql As String = "INSERT INTO tblRecords(ID,ID_NO,NAME,TI1,Q1,QR1,TI2,Q2,QR2,TI3,Q3,QR3,TI4,Q4,QR4,TI5,Q5,QR5,QR) VALUES(#IDDataGridViewTextBoxColumn,#IDNODataGridViewTextBoxColumn,#NAMEDataGridViewTextBoxColumn,#TI1DataGridViewTextBoxColumn,#Q1DataGridViewTextBoxColumn,#QR1DataGridViewTextBoxColumn,#TI2DataGridViewTextBoxColumn,#Q2DataGridViewTextBoxColumn,#QR2DataGridViewTextBoxColumn,#TI3DataGridViewTextBoxColumn,#Q3DataGridViewTextBoxColumn,#QR3DataGridViewTextBoxColumn,#TI4DataGridViewTextBoxColumn,#Q4DataGridViewTextBoxColumn,#QR4DataGridViewTextBoxColumn,#TI5DataGridViewTextBoxColumn,#Q5DataGridViewTextBoxColumn,#QR5DataGridViewTextBoxColumn,#QRDataGridViewTextBoxColumn)"
Cmd = New OleDbCommand(sql, Cnn)
For Each row As DataGridViewRow In dgvRecords.Rows
'ADD Parameters
Cmd.Parameters.AddWithValue("#ID", row.Cells("IDDataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("IDNODataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("NAMEDataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("TI1DataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("Q1DataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("QR1DataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("TI2DataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("Q2DataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("QR2DataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("TI3DataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("Q3DataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("QR3DataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("TI4DataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("Q4DataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("QR4DataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("TI5DataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("Q5DataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("QR5DataGridViewTextBoxColumn").Value)
Cmd.Parameters.AddWithValue("#ID", row.Cells("QRDataGridViewTextBoxColumn").Value)
Next
Try
Cnn.Open()
If Cmd.ExecuteNonQuery() > 0 Then
MsgBox("Successfully saved.")
End If
Cnn.Close()
Catch ex As Exception
MsgBox(ex.Message)
Cnn.Close()
End Try
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Me.Validate()
Me.da.Update(Me.ds.Tables("tblRecords"))
Me.ds.AcceptChanges()
End Sub
End Class

VS/SQLServer can't update database using combobox as datatable

This are my code, It worked perfectly except for ONE. I can't update:
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim con As SqlConnection
Dim Cmd As SqlCommand
Dim Query As String
Sub disk()
con = New SqlConnection
con.ConnectionString = "Server=Jansen\SQLEXPRESS;Database=AJLMNewProjectDatabase;Trusted_Connection=True;"
Try
con.Open()
Dim READER As SqlDataReader
Query = "UPDATE AdminESP SET Benefactor='" & CmbBenefactor.Text & "' WHERE ExternalSP='" & CmbExternalSP.Text & "'"
Cmd = New SqlCommand(Query, con)
READER = Cmd.ExecuteReader()
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
con.Close()
End Sub
Sub dis()
CmbExternalSP.Items.Clear()
CmbBenefactor.Items.Clear()
con = New SqlConnection
con.ConnectionString = "Server=Jansen\SQLEXPRESS;Database=AJLMNewProjectDatabase;Trusted_Connection=True;"
Try
con.Open()
Dim READER As SqlDataReader
Query = "select * from [AJLMNewProjectDatabase].[dbo].[AdminESP]"
Cmd = New SqlCommand(Query, con)
READER = Cmd.ExecuteReader()
While READER.Read
Dim ESP = READER.GetString(1)
Dim Ben = READER.GetString(2)
CmbExternalSP.Items.Add(ESP)
CmbBenefactor.Items.Add(Ben)
End While
con.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con = New SqlConnection
con.ConnectionString = "Server=Jansen\SQLEXPRESS;Database=AJLMNewProjectDatabase;Trusted_Connection=True;"
Try
con.Open()
Dim READER As SqlDataReader
Query = "select * from AdminESP"
Cmd = New SqlCommand(Query, con)
READER = Cmd.ExecuteReader()
While READER.Read
Dim ESP = READER.GetString(1)
Dim Ben = READER.GetString(2)
CmbExternalSP.Items.Add(ESP)
CmbBenefactor.Items.Add(Ben)
End While
con.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
Private Sub CmbExternalSP_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbExternalSP.SelectedIndexChanged
CmbBenefactor.SelectedIndex = CmbExternalSP.SelectedIndex
End Sub
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click
con = New SqlConnection("Server=Jansen\SQLEXPRESS;Database=AJLMNewProjectDatabase;Trusted_Connection=True;")
con.Open()
Cmd = con.CreateCommand
Cmd.CommandText = String.Format("INSERT INTO AdminESP(ExternalSP, Benefactor) " &
"VALUES('{0}', '{1}')",
CmbExternalSP.Text,
CmbBenefactor.Text) ' To Save data to ExternalSP DataTable
Dim rowsAffected As Integer = Cmd.ExecuteNonQuery()
If rowsAffected > 0 Then
MsgBox("Program Added!")
Else
MsgBox("Failed to Add")
End If
CmbExternalSP.Text = ""
CmbBenefactor.Text = ""
con.Close()
End Sub
Private Sub BtnRefresh_Click(sender As Object, e As EventArgs) Handles BtnRefresh.Click
CmbExternalSP.DropDownStyle = ComboBoxStyle.DropDown
CmbBenefactor.DropDownStyle = ComboBoxStyle.DropDown
CmbExternalSP.Text = ""
CmbBenefactor.Text = ""
End Sub
Private Sub BtnRemove_Click(sender As Object, e As EventArgs) Handles BtnRemove.Click
con = New SqlConnection
con.ConnectionString = "Server=Jansen\SQLEXPRESS;Database=AJLMNewProjectDatabase;Trusted_Connection=True;"
Try
con.Open()
Dim READER As SqlDataReader
Query = "DELETE FROM AdminESP WHERE ExternalSP='" + CmbExternalSP.Text + "'"
Cmd = New SqlCommand(Query, con)
READER = Cmd.ExecuteReader()
If MessageBox.Show("You are about to remove a Program, Please confirm your Action.", "DELETE", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.OK Then
MsgBox("Program Removed")
End If
CmbExternalSP.Text = ""
CmbBenefactor.Text = ""
CmbExternalSP.DropDownStyle = ComboBoxStyle.DropDownList
CmbBenefactor.DropDownStyle = ComboBoxStyle.DropDownList
Call dis()
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
con.Close()
End Sub
Private Sub BtnUpdate_Click(sender As Object, e As EventArgs) Handles BtnUpdate.Click
con = New SqlConnection
con.ConnectionString = "Server=Jansen\SQLEXPRESS;Database=AJLMNewProjectDatabase;Trusted_Connection=True;"
Try
con.Open()
Dim READER As SqlDataReader
Query = "UPDATE AdminESP SET ExternalSP='" & CmbExternalSP.Text & "' WHERE Benefactor='" & CmbBenefactor.Text & "'"
Cmd = New SqlCommand(Query, con)
READER = Cmd.ExecuteReader()
MessageBox.Show("Program Updated.")
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
con.Close()
End Sub
Private Sub BtnR_Click(sender As Object, e As EventArgs) Handles BtnR.Click
Call dis()
End Sub
Private Sub CmbBenefactor_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbBenefactor.SelectedIndexChanged
CmbExternalSP.SelectedIndex = CmbBenefactor.SelectedIndex
End Sub
End Class
Now my problem is, When I click UPDATE button, only one column which is under combobox 1 updates; the other combobox doesn't change at all.

Data updation and deletion error

I have a DataGrid and many text fields to add data into the database. When i add a new data, it gets updated in the database and in the data grid.But when i delete the data, it gets deleted only from the database. It doesn't get updated in the data grid.
When i try to update the data, it updates only one record at a time.when i try for another record it gives me a error "The variable name '#date' has already been declared. Variable names must be unique within a query batch or stored procedure." I have to close and reopen the form to update a new record.
Imports System.Data.SqlClient
Public Class Form
Dim con As New SqlClient.SqlConnection("Server = DEL-PC; Database=Shj; Trusted_Connection=yes;")
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim ds As DataSet
Dim da As SqlDataAdapter
Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SqlDataAdapter1.Fill(DataSet11)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles newbtn.Click
If RegNoTextBox.Text <> "" Then
cmd.Connection = con
con.Open()
cmd.CommandText = "insert into WaterProofing(Date,RegNo) values ('" & DateDateTimePicker.Value & "','" & RegNoTextBox.Text & "')"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
Else
MessageBox.Show("Please enter registration number")
End If
End Sub
//updation
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles editbtn.Click
cmd.Parameters.AddWithValue("#date", DateDateTimePicker.Value)
cmd.Parameters.AddWithValue("#regno", RegNoTextBox.Text)
cmd.Connection = con
con.Open()
cmd.CommandText = "update WaterProofing set RegNo= #regno where date=#date"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
MessageBox.Show("Details Updated!")
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deletebtn.Click
cmd.Connection = con
con.Open()
cmd.CommandText = "delete from WaterProofing where date='" & DateDateTimePicker.Value & "'"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
MessageBox.Show("Details Deleted!")
End Sub
Sub showdata()
SqlDataAdapter1.Fill(DataSet11, "WaterProofing")
With DataGridView
.Update()
End With
End Sub
End Class
Please help me in deletion and updating.
You're adding parameters before declaring CommandText at Button2_Click
Try it in this way:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles editbtn.Click
Try
Dim command As New SqlCommand
con.Open()
command.Connection = con
command.CommandText = "update WaterProofing set RegNo= #regno where date=#date"
command.Parameters.AddWithValue("#date", DateDateTimePicker.Value)
command.Parameters.AddWithValue("#regno", RegNoTextBox.Text)
command.ExecuteNonQuery()
con.Close()
Call showdata()
MessageBox.Show("Details Updated!")
Catch ex as Exception
MessageBox.Show(ex.Message)
End try
End Sub
UPDATE
Basically you have to do the same thing when you load the DataGridView for the first time in order to refresh the DataGridView with the current data from database after deleting or updating records, so your ShowData Sub might look something like this
Private Sub ShowData()
Dim Connection As SqlConnection
Connection = New SqlConnection("YourConnectionString")
Try
Connection.Open()
Dim SQL As String = "SELECT Field1, Field2, Field3 FROM Table"
Dim DS As New DataSet
Dim Adapter As New SqlDataAdapter(SQL, Connection)
Adapter.Fill(DS)
DataGridView.DataSource = DS.Tables(0)
DataGridView.Refresh()
Catch ex As Exception
MessageBox(ex.Message)
Finally
Connection.Close()
End Try
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deletebtn.Click
Try
Dim command As New SqlCommand
con.Open()
command.Connection = con
command.CommandText = "delete from WaterProofing where date='" & DateDateTimePicker.Value & "'"
command.ExecuteNonQuery()
con.Close()
Call ShowData_Delete()
MessageBox.Show("Details Deleted!")
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
End Try
End Sub
Private Sub ShowData_Delete()
Dim Connection As SqlConnection
Try
Connection = New SqlConnection("Server = DEL-PC; Database=Shj; Trusted_Connection=yes;")
Connection.Open()
Dim SQL As String = "SELECT * from WaterProofing"
Dim DS As New DataSet
Dim Adapter As New SqlDataAdapter(SQL, Connection)
Adapter.Fill(DS)
DataGridView1.DataSource = DS.Tables(0)
DataGridView1.Refresh()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
Connection.Close()
End Try
End Sub