Can not Search in and Edit DB in the same times (and same Windows Form) by using DataGridView - vb.net

I'm have DataGridView in a Windows Form with some data in it and I have button for edit, I want to search for row by using TextBox and button and when I find the wanted row I will change it and click edit button,when I edit any row (without using search button) and press edit the DB is Updated , my problem is that: when I search for specific row and find it then edit the data and press edit button the data in DB don't updated, please help, I'm use this code:
Imports System.Data.SqlClient
Public Class Form9
Private sqlConn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Clinic System\Clinic System\ClinicDB.mdf;Integrated Security=True;User Instance=True")
Private cmdSelect, cmdDelete As String
Private daEmployees As New SqlDataAdapter("Select * From History", sqlConn)
Private sqlCmndBuilder As New SqlCommandBuilder(daEmployees)
Private myDS As New DataSet
Private Sub HistoryBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Validate()
Me.HistoryBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.ClinicDBDataSet3)
End Sub
Private Sub Form9_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
daEmployees.Fill(myDS, "History")
HistoryDataGridView.DataSource = myDS.Tables(0)
End Sub
Private Sub ButtonSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSearch.Click
Try
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Clinic System\Clinic System\ClinicDB.mdf;Integrated Security=True;User Instance=True")
Dim d1 As New SqlDataAdapter("Select * from History Where Name like '%" & TextBox1.Text & "%'", con)
Dim d2 As New DataTable
d1.Fill(d2)
HistoryDataGridView.DataSource = d2
Catch ex As Exception
MessageBox.Show("Err.Discription")
End Try
End Sub
Private Sub ButtonEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonEdit.Click
daEmployees.Update(myDS.Tables(0))
MsgBox("Patient Details Updated!")
End Sub

Your issue is rather simple - you trying to update wrong table
daEmployees.Update(myDS.Tables(0))
While you need to update d2
In form scope
Dim _isSearch as boolean
On Form9_Load and when you reload as well
_isSearch = false
Here what you can do - In ButtonSearch_Click
_isSearch = true
If myDS.Tables.Contains("SEARCH_TBL") Then
myDS.Tables.Remove("SEARCH_TBL")
End if
Dim d2 As DataTable = myDS.Tables.Add("SEARCH_TBL")
d1.Fill(d2)
In ButtonEdit_Click
if _isSearch then
daEmployees.Update(myDS.Tables("SEARCH_TBL"))
else
daEmployees.Update(myDS.Tables(0))
End if
I think, daEmployees should update "SEARCH_TBL" because result set identical to first table. If not, just take your other adapter to a form scope.
But really, you can reuse the grid and update button, but you need to create logic tracking which table is currently loaded.

Related

SQL Column to TextBox (from ComboBox)

I have managed to add data into a ComboBox from a column out of my SQL table, but I need the rows from across to display in the rest of the textboxes. (I hope I have worded this correctly).
Here is my code currently:
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
Dim dt As New DataTable
da.Fill(dt)
ComboBox1.DisplayMember = "DISPLAY_NAME"
ComboBox1.DataSource = dt
End Sub
The above works with no issues, all of the items add into the ComboBox but I need the corresponding rows from the other two columns which are EMAIL_ADDRESS and DEPARTMENT to add into TextBoxes from what is selected in the ComboBox.
Under the SelectedIndex_Changed event of the ComboBox; Enter the following code.
Dim dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
da.Fill(dt)
ComboBox1.DisplayMember = "DISPLAY_NAME"
ComboBox1.DataSource = dt
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Textbox1.Text = CStr(dt.Rows(ComboBox1.SelectedIndex)("EMAIL_ADDRESS"))
Textbox2.Text = CStr(dt.Rows(ComboBox1.SelectedIndex)("DEPARTMENT"))
End Sub
You Will need to declare the data table dt outside your form's load event so it can be visible to the SelectedIndex_Changed event of the combo box.
I suggest you to use BindingSource to get it done.
Try this:
1- Declare your variable type of BindingSource with events. Also, declare your dataset will be used for data.
Dim WithEvents BS As New BindingSource
Dim ds As New DataSet
2- In your Form Load Event, query your data and bind it with both Binding Source and your ComboBox control.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
da.Fill(ds, "myPopulatedTable")
ComboBox1.DisplayMember = "id"
ComboBox1.DataSource = ds.Tables("myPopulatedTable")
'Here the new code'
BS.DataSource = ds
BS.DataMember = "myPopulatedTable"
End Sub
3- Add a Sub Procedure to display your data into other text boxes controls.
Private Sub DISPLAYRECORD(Optional ByVal table As String = "myPopulatedTable")
TextBox1.Text = ds.Tables(table).Rows(Me.BS.Position)("column1").ToString
TextBox2.Text = ds.Tables(table).Rows(Me.BS.Position)("column2").ToString()
TextBox2.Text = ds.Tables(table).Rows(Me.BS.Position)("column3").ToString()
End Sub
4- In the PositionChanged event of your Binding Source, call that sub procedure (above)
Private Sub BS_PositionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles BS.PositionChanged
DISPLAYRECORD()
End Sub
5- Finally, to sync your data with ComboBox selection, you need to change the position of that Binding Source according to the ComboBox index selection
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
BS.Position = ComboBox1.SelectedIndex
End Sub

How to update SQLite database from DataGridView in Visual Basic 2013 .net?

I am displaying data from SQLite table into a DataGridView as following -
Private Sub Subjects_Manager_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con = New SQLiteConnection("Data Source = c:\demo\test.db;Version=3;")
con.Open()
sql = "SELECT * FROM med_subjects"
da = New SQLiteDataAdapter(sql, con)
da.Fill(ds, "SubjectsList")
DataGridView1.DataSource = ds.Tables("SubjectsList").DefaultView
With DataGridView1
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Subject Id"
.Columns(1).HeaderCell.Value = "Subject Name"
End With
DataGridView1.Sort(DataGridView1.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
con.close()
End Sub
I want to save changes done in DataGridView (either Updation of Row/s or Insertion of Row/s) back to SQLite table. But I couldn't find a way to do so.
Edit 1 :
I know Insert/Update Queries of SQLite, but what I don't know is how & where to keep them so that they can be triggered in responses to changes made in DataGridView. e.g.
' I am using this variable for demonstration, in reality InsertSubjectSqlString will be equal to changes done in DataGridView
Dim InsertSubjectSqlString As String = "Insert into med_subjects (Subject_Name) Values ('_Miscellaneous')"
Dim SqliteInsertRow As SQLiteCommand
SqliteInsertRow = con.CreateCommand
SqliteInsertRow.CommandText = InsertSubjectSqlString
SqliteInsertRow.ExecuteNonQuery()
But I don't know, where should I put it?
Edit 2:
After seeing comments and answers, I came to know that there is No direct way to Insert/Update Sqlite database from DataGridView. So I was curious, if there is any event like RowSelected which would
trigger on selecting a row and get that row's data
then taking the row's data into multiple text boxes and lastly
triggering Insert/Update queries taking values from these textboxes
by a button
I know it's highly hypothetical with NO sample codes, but it's because I am asking for Event name.
Call this on LeaveRow event or CellEndEdit
Private Sub DataGridView1_RowLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowLeave
Dim i as integer
Try
for i = 0 to datagrid.rows.count-1
myUpdate(datagrid.item(0,i).tostring() , datagrid.item(1,i).tostring())
next
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
note , you can also give the column name of your grid in place of column index , like this datagrid.item("fname",i).tostring()
Here we will save in database:
Sub myUpdate(byval fname as string , byval lname as string)
Try
dim con as new sqlconnection("you connection string")
dim cmd as new sqlcommand
con.open()
cmd.connection= con
cmd.commandtext="insert into table (fname,lname) values (#fname,#lname)"
cmd.Parameters.AddWithValue("#fname", fname)
cmd.Parameters.AddWithValue("#lname", lname)
cmd.ExecuteNonQuery()
Con.close()
Catch ex As Exception
MsgBox(Err.Description)
End Try
End sub
I hope this will help you to solve !
There are many ways to manipulate data .
CristiC
I dont think you will find some magic way that the DataGridView and DataTable are going to persist things automatically to the backend SQLite database. As you are hinting at I think you will have to rely on events.
I think the event you are missing is answered here stackoverflow cell value changed event
Ok I think is better to use CellEndEdit, because LeaveRow is triggered only if you click on other row.
Look on this example.
you must use: da.Update(ds.Tables("SubjectsList").DefaultView)
Imports System.Data.SqlClient
Public Class Form1
Const connectionstring As String = "server=(local);database=TestDB;uid=sa;pwd=sa;"
Private SQL As String = "select * from customer"
Private con As New SqlConnection(connectionstring)
Private dt As New DataTable
Private adapter As New SqlDataAdapter(SQL, con)
Private commandbuilder As New SqlCommandBuilder(adapter)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
adapter.Fill(dt)
DataGridView1.DataSource = dt
End Sub
Private Sub DataGridView1_RowLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowLeave
adapter.Update(dt)
End Sub
End Class
Please use this code hopefully it will work
Imports System.Data.SQLite
Public Class Form
Dim con As New SQLite.SQLiteConnection
Dim da As New SQLite.SQLiteDataAdapter
Dim dt As New DataTable
Dim cmdbl As New SQLite.SQLiteCommandBuilder
Dim dlgResult As DialogResult
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
dlgResult = MessageBox.Show("Do you want to save the changes you made?", "Confirmation!", MessageBoxButtons.YesNo)
If dlgResult = DialogResult.Yes Then
Try
con.Open()
cmdbl = New SQLiteCommandBuilder(da)
da.Update(dt)
MsgBox("Updated successfully!")
con.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End If
End Sub
End Class

Datagridview and access database only updates after clicking a different row

I am reading an access database and populating the info in datagridview. My form has a DGV, and 3 buttons.
Button one copies the selected row to a datetimepicker control.
Button two copied the updated datetimepicker value back to the DVG
Button three does an update (writes the info back to the database).
My issue is that the info only gets updated in the database if I select a different row before hitting button three. I am not getting any error message in either case.
Below is my code. The database only has 2 columns (name and DOB - which is date/time).
Public Class Form1
Dim dbConn As New OleDb.OleDbConnection
Dim sDataset As New DataSet
Dim sDataAdapter As OleDb.OleDbDataAdapter
Dim sql As String
Dim iTotalRows As Integer
Dim sShipTypeFilter As String
Dim sBuildingFilter As String
Dim sCustSuppFilter As String
Dim sStatusFilter As String
Dim sDayFilter As String
Dim dv As New DataView
Sub myDBConn()
dbConn.ConnectionString = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\terry\Documents\Database1.accdb"
Debug.Print("Start:" & DateAndTime.Now.ToString)
dbConn.Open()
sql = "select * from TableX"
sDataAdapter = New OleDb.OleDbDataAdapter(Sql, dbConn)
sDataAdapter.Fill(sDataset, "MyTable")
dbConn.Close()
iTotalRows = sDataset.Tables("MyTable").Rows.Count
Debug.Print("Rows from Access:" & iTotalRows)
Debug.Print("End:" & DateAndTime.Now.ToString)
End Sub
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Call myDBConn()
Debug.Print("DVG1 row count before binding:" & DataGridView1.Rows.Count)
'dv = New DataView(sDataset.Tables(0), "Shipment = 'Regular' and Building = 'CSE'", "Company DESC", DataViewRowState.CurrentRows)
dv = sDataset.Tables(0).DefaultView
Debug.Print("DataView count:" & dv.Count)
DataGridView1.DataSource = dv
Debug.Print("DVG1 Rows:" & DataGridView1.Rows.Count)
DataGridView1.Columns("DOB").DefaultCellStyle.Format = "hh:mm tt"
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
dtp1.Value = DataGridView1.SelectedRows(0).Cells("DOB").Value
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
DataGridView1.SelectedRows(0).Cells("DOB").Value = dtp1.Value
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Debug.Print("switched row")
Me.Visible = False
Dim sqlcb As New OleDb.OleDbCommandBuilder(sDataAdapter)
sDataAdapter.Update(sDataset.Tables("MyTable"))
Me.Close()
End Sub
End Class
Before updating you need to Endedit. This means you need to add Endedit for the datagridview.
So this will be your code:
Debug.Print("switched row")
Me.Visible = False
Dim sqlcb As New OleDb.OleDbCommandBuilder(sDataAdapter)
Datagridview1.EndEdit()
sDataAdapter.Update(sDataset.Tables("MyTable"))
Me.Close()
EDIT1:
Dim dt As New DataTable
dbConn.Open()
sDataset.Tables.Add(dt)
sDataAdapter = New OleDbDataAdapter("Select * from TableX", dbConn)
sDataAdapter.Update(dt)
dbConn.Close()
I figured it out - thanks Stef for putting me on the right track.
My DGV is only updated programmatically (not by user edits) so I updated the code for button 2 to set the editmode, begin editing, update the selected DVG row and end editing:
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
DataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically
DataGridView1.BeginEdit(True)
DataGridView1.SelectedRows(0).Cells("DOB").Value = dtp1.Value
DataGridView1.EndEdit()
End Sub
After doing this modification - my datadapter.update command works!!

Filtering Datagridview From Datagridview Not From Database

i want to filter datagridview on my form..
on the form :
1 datagridview
1 label
1 timer
i have loaded database into datagridview (all data to datagridview)
on my datagridview i have 7 column the last column is date with format dd/MM/yyyy, and now how to filtering datagridview with label, i set this label to date like this
Private Sub TimerDate_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerDate.Tick
Dim FDate As String = Format(Today, "dd/MM/yyyy")
LblDate.Text = FDate
End Sub
and i want to eliminate the other data.. sooo in the end in my datagridview i have data with the last column same as LblDate.text
i dont want to filter datagridview from database.
can someone help me..? thanks.
sorry for my bad english.
this is how i populating data to datagrid
Public Class FrmJadwalSidang
Dim ConnString As String = ("Dsn=SqlConn;Server=192.168.100.1;uid=XXX;pwd=XXX;database=DBXXX;port=3306")
Public Function FillData(ByVal Sqlstring As String)
Dim OdbcConn As OdbcConnection = New OdbcConnection(ConnString)
OdbcConn.Open()
Dim MyDataSet As DataSet = New DataSet()
Dim MyOdbcdAdapter As OdbcDataAdapter = New OdbcDataAdapter()
MyOdbcdAdapter.SelectCommand = New OdbcCommand(Sqlstring, OdbcConn)
MyOdbcdAdapter.Fill(MyDataSet)
Me.DATAGRIDVIEW.DataSource = MyDataSet.Tables(0)
MyOdbcdAdapter.Dispose()
MyDataSet.Dispose()
OdbcConn.Close()
OdbcConn.Dispose()
End Function
Private Sub FrmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FillData("Select nomor_perkara, jam_sidang, para_pihak, majelis_hakim_text, panitera_pengganti_text, agenda, tanggal_sidang from v_jadwal_sidang")
End Sub
End Class
SOLVED
Private Sub FrmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FillData("Select nomor_perkara, jam_sidang, para_pihak, majelis_hakim_text, panitera_pengganti_text, agenda, tanggal_sidang from v_jadwal_sidang WHERE jadwal_sidang='" & LblDate.text.tostring & "'")
end sub
it work. in the end i have to filtering by the sql query..
thanks to someone who gives me the answer.
if you are using a SqlDataSource, set the FilterExpression of the control.
See this: How to: Enable Filtering for the SqlDataSource Control
And this: How to: Connect to an ODBC Database Using the SqlDataSource Control
EDIT : I provided the information for a web application not a winform application. Please read this for info on how to set up filtering for a BindingSource: BindingSource.Filter Property

invalid operation exception was unhandled Update requires a valid UpdateCommand

From these codes, I want to edit, add and save data from VB to MS Access permanently. I created dozens of Visual Basic projects but no progress at all.
Public Class Form1
Private Sub ProductDescBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProductDescBindingNavigatorSaveItem.Click
Me.Validate()
Me.ProductDescBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.INVSYSDataSet)
End Sub
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 'INVSYSDataSet.ProductDesc' table. You can move, or remove it, as needed.
Me.ProductDescTableAdapter.Fill(Me.INVSYSDataSet.ProductDesc)
End Sub
End Class
The problem is that "invalid operation exception was unhandled" appears, Update requires a valid UpdateCommand from code Me.TableAdapterManager.UpdateAll(Me.INVSYSDataSet)
If you need the DataSource, I can provide code from another VB project.
*updated second code, help for sql please
*updated srry bout that
Public Class Add_Products
Private myConString As String
Private con As OleDb.OleDbConnection = New OleDb.OleDbConnection
Private Dadapter As OleDb.OleDbDataAdapter
Private DSet As DataSet
Private DSet2 As DataSet
Private ConCMD As OleDb.OleDbCommand
Dim strSql As String
Dim inc As Integer
Dim MaxRows As Integer
Private Sub Add_Products_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\larca\Documents\Visual Studio 2010\Projects\march16\march16\obj\x86\Debug\INVSYS.mdb"
con.ConnectionString = myConString
con.Open()
Dadapter = New OleDb.OleDbDataAdapter("select * from ProductDesc", con)
DSet = New DataSet
Dadapter.Fill(DSet, "ProductDesc")
DataGridView1.DataSource = DSet.Tables("ProductDesc")
con.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Using con = New OleDb.OleDbConnection(myConString)
con.Open()
Dim cmd As OleDb.OleDbCommand
cmd = New OleDb.OleDbCommand("UPDATE ProductDesc", con)
Dadapter.UpdateCommand = cmd
Dadapter.Update(DSet, "ProductDesc")
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
The error message is telling you that you have not defined an Update command for the DataAdapter. From DbDataAdapter.Update Method DataSet, String: If INSERT, UPDATE, or DELETE statements have not been specified, the Update method generates an exception.
To resolve this, assign the UpdateCommand an OleDbCommand object with your update logic, like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Using con = New OleDb.OleDbConnection(myConString)
con.Open()
Dim cmd As OleDbCommand
cmd = New OleDbCommand("<your update SQL goes here>", con)
DAdapter.UpdateCommand = cmd
Dadapter.Update(DSet, "ProductDesc")
End Using
End Sub
Simply put your SQL in the OleDbCommand and assign it to the UpdateCommand property.
Look at this link for a detailed example (and be sure to use parameterized queries like in the example to avoid SQL Injection attacks): OleDbDataAdapter.UpdateCommand Property