Changes in Datagridview not saving in table SQLite vb.net - vb.net

I'm trying to save changes made to datagridview into the table tbl_invent, the changes i make commits to datagridview but it does not save to the table (database), also it doesn't have any error, all i received is a message saying "Records Updated = 0". anyone could point me to the right direction?
Dim da As New SQLiteDataAdapter("select * from tbl_Invent", connection)
Dim ds As New DataSet
'Dim cmdbuilder As New SQLite.SQLiteCommandBuilder(da)
Dim i As Integer
da.TableMappings.Add("tbl_Invent", "tbl_Invent") 'add due to error unable to Update unable to find TableMapping['Table'] or DataTable 'Table'
Try
i = da.Update(ds, "tbl_Invent")
MsgBox("Records Updated= " & i)
Catch ex As Exception
MsgBox(ex.Message)
End Try
connection.Close()
i already check out this thread:
How to save changes from DataGridView to the database?
-and-
Datagridview save changes to Database vb.net
thank you very much in advance.

It should be obvious that you're not going to save any changes if you don't make any changes between creating/populating your DataTable and trying to save the changes. You need to create the DataTable, populate it and bind it in one method (probably the Load event handler of the form), then the user makes the changes, then you save the changes from the same DataTable in another method (probably the Click event handler of a Button. E.g.
Private table As New DataTable
Private adapter As New SqlDataAdapter("SQL query here", "connection string here")
Private builder As New SqlCommandBuilder(adapter)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
adapter.Fill(table)
BindingSource1.DataSource = table
DataGridView1.DataSource = BindingSource1
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BindingSource1.EndEdit()
adapter.Update(table)
End Sub
The DataTable is created when the form is, the user makes the changes in the grid and clicks the Button and then you save the changes from THE SAME DataTable, not a new one that you just created that contains no changes.

Related

Update database table from DataGridView using DataAdapter

EDIT: This was resolved by querying the table directly rather than by using a stored procedure and ref cursor.
I have a form which only contains a DataGridView dgvDetail. This is the form class code:
Imports Oracle.ManagedDataAccess.Client
Public Class FRM_EditDetail
Dim DataAdapter As New OracleDataAdapter
Dim CommandBuilder As New OracleCommandBuilder(DataAdapter)
Dim Connection As New OracleConnection(connectionString)
Dim Command As OracleCommand = Connection.CreateCommand()
Private Sub FRM_EditDetail_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Connection.Open()
Command.CommandType = CommandType.StoredProcedure
Command.CommandText = "SV_PACKAGE.GetDetail"
Command.Parameters.Add("P_CURSOR", OracleDbType.RefCursor).Direction = ParameterDirection.Output
DataAdapter.SelectCommand = Command
DataAdapter.Fill(dsData, "Detail")
dsData.Tables("Detail").PrimaryKey = New DataColumn() {dsData.Tables("Detail").Columns("ID")}
dgvNHHDetail.DataSource = dsData.Tables("Detail")
End Sub
Private Sub FRM_EditDetail_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
CommandBuilder.GetUpdateCommand()
DataAdapter.Update(dsData, "Detail")
Connection.Close()
End Sub
End Class
I want the user to open the form, change the data, and when they close the form the changes are passed into the database table.
The Load event works correctly in so far as dgvDetail is populated from the database table correctly. I get no error on the dsData.Tables("Detail").PrimaryKey = New DataColumn() {dsData.Tables("Detail").Columns("ID")} line, and my database table has a primary key of the same column.
However the FormClosing event triggers, get the Dynamic SQL generation failed. No key information found.
What am I doing wrong with assigning a primary key (or something else)?

how to pass multiple values using single textbox in vb.net?

I am doing vb.net programming. In that, I am using one textbox, one gridview and one button. Now, I want to pass queries into the textbox and when clicking on button, I want to display the result into the datagridview.
i.e suppose i am passing selection query and clicking on button at that time i want to display the table data into the datagridview.
I don't know what Db you are using but I have an example using Sql.
Example:
You want to get the Name from the Students Db.
Dim dt As New DataTabale
Dim con As New SqlConnection("connection")
Dim cmd As New OdbcCommand("SELECT * FROM [Students] WHERE [Name] = #Name", con)
con.Open()
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = TextBox.Text
dt.Load(cmd.ExecuteReader())
GridView1.DataSource = dt
GridView.DataBind()
You can place this code on Button.
Ps. I view your the edit history of your code and I saw that you are using Db.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim query As String = TextBox1.Text
Try
SqlDataSource1.SelectCommand = query
SqlDataSource1.DataBind()
Catch ex As Exception
MsgBox("No results returned")
End Try
End Sub

Making a Datatable's content appear in a DataGridView

I am continuing my rewrite of an old VB6 into .Net as part of my .Net learning. I have managed to read a CSV file into a Datatable, and I can view it has populated properly using the 'datatable visualiser' when I look at 'dt', but it doesn't seem to populate the DataGridView control I am trying to tie it to. I have spent a couple of hours browsing other threads and trying things, but I cannot see what I am doing wrong. The DataGridView is on another form in the App, and I am reading the CSV file (a config file of sorts) from the main MDI form. When I show the child form containing the DataGridView it is always empty (it actually seems to have added the two datatable rows, but their content is all blank).
Public dt As New DataTable
Public ThisFilename As String = "c:\SitesDB.cfg"
Private Sub GetSitesDB()
Dim sr As New IO.StreamReader(ThisFilename)
Dim newline() As String = sr.ReadLine.Split(","c)
dt.Columns.AddRange({New DataColumn(newline(0)), New DataColumn(newline(1)), New DataColumn(newline(2)), New DataColumn(newline(3)),
New DataColumn(newline(4)), New DataColumn(newline(5)), New DataColumn(newline(6)), New DataColumn(newline(7)), New DataColumn(newline(8)),
New DataColumn(newline(9)), New DataColumn(newline(10)), New DataColumn(newline(11))})
While (Not sr.EndOfStream)
newline = sr.ReadLine.Split(","c)
Dim newrow As DataRow = dt.NewRow
newrow.ItemArray = {newline(0), newline(1), newline(2), newline(3), newline(4), newline(5), newline(6), newline(7), newline(8), newline(9), newline(10), newline(11)}
dt.Rows.Add(newrow)
End While
Form1.DataGridView1.DataSource = dt ' data can be seen here using datatable visualiser hovering over 'dt'
End Sub
Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
Form1.Show()
End Sub
I have tried refreshing the DataGridView, to no avail. I am wondering if its something to do with Form1.Show() being actioned after the datatable is tied to the DataGridView?
But the following didn't help
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' chkBit.Checked = False
' Dim cfgtext As String : cfgtext = ""
DataGridView1.DataSource = NAMS.dt
End Sub

How can I have 2 gridviews in one form with same dataset, but other population?

Here you see my code of a form with 2 gridviews. Both have the same dataset, bindingsource. The dataset which is made out of a datasource, has 2 different sql queries.
filld() and fillauswahl() filld shows in the gridview a "select distinct" query.
When the user hits the button1, the selected item from that gridview is saved in "verzeichnis1" this var gets pasted to fillauswahl() which is
select* from mytable where columnx = verzeichnis1
The problem I have is that both gridviews get filled during formload with filld() and by clicking the button with fillverzeichnis() i dont know how to seperate that!? i guess it´s very easy. Cheers and thanks
Public Class Importverzeichnis
Public verzeichnis1 As String
Private Sub Importverzeichnis_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Me.SKM2TableAdapter.Filld(Me.SLXADRIUMDEVDataSet.SKM2)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each cell As DataGridViewCell In DataGridView1.SelectedCells
verzeichnis1 = cell.Value
Next
Me.SKM2TableAdapter.Fillauswahl(Me.SLXADRIUMDEVDataSet.SKM2, verzeichnis1)
End Sub
End Class
Edit: I created a new connection a new datset and new dataadapter and now it works:
Dim connectionString As String = My.Settings.SLXADRIUMDEVConnectionString
Dim sql As String = "SELECT * FROM SKM2 where
Benutzerdefiniert_10 ='" & verzeichnis1 & "' "
Dim connection As New SqlConnection(connectionString)
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "verzeichnis")
connection.Close()
datagridview2.DataSource = ds
datagridview2.DataMember = "verzeichnis"
but I would be more happy if can use my first dataset and my first adapter. If anyobdy knows how I can do this, I would be happy for the answer
To me the best way would be to just pull down the data as a your normal select statement and then filter the data in your code-behind. By populating a dataset with the same data twice your just making the traffic from the database slower. However, if you wish to keep your current dataset, I would assume that there are two tables in it, one for each select. If that is the case then change:
datagridview2.DataSource = ds
to:
datagridview2.DataSource = ds.Tables(1) 'assumes the second table is used for this datasource

How to refresh a DataGridView when a dialog form is closed

I am trying to refresh a datagirdview when i add a new record using a dialog form. I would like to know how can i refresh my datagirdview. I have two Win Forms . Form A is called FrmContactDetailList which is having a datagridview which i is showing data from sql server. Below first block of code is used to bind data to the grid. which is given in form load event and also in this form i have a Button called "Add New Record" . Once i press this button its opening a win form which is opening another form. Below is that code which i used to open this in by button click event.
This will open Form B. Form is called FrmClientDetails. This form will have a text box and a save button . So once i enter the new name in the text box and press save i want the datagirdview which is in Form A to be updated . and show the new record once i close Form B. how can i achieve this.
This Code is used to bind the datagridview. I have given this is the form load event.
Sub GetContactList()
Dim BindData As New VoucherClass
Dim dt As DataTable = BindData .Get_Client_List
DataGridView.DataSource = dt
End Sub
Private Sub FrmContactDetailsList_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
GetContactList()
End Sub
I have using this code to open the dialog form to enter the new data.
Private Sub BtnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnOpen.Click
Dim FrmNewContact As New FrmClientDetails
FrmNewContact.Owner = Me
FrmNewContact.ShowDialog()
End Sub
When the binding data change it is automatically reflected to the data grid view that is bond.
Edit:
Handle the FrmNewContact's Closing event. You can refresh your datagridview in that sub.
Dim WithEvents dialog As New FrmNewContact
Sub done() Handles dialog.FormClosed
Me.DataGridView1.Refresh()
End Sub
Next edit:
Dim BindData As New VoucherClass
Dim dt As DataTable = BindData .Get_Client_List
Declare them outside of the sub. So you should have this:
Dim BindData as VoucherClass
Dim dt as DataTable
Sub GetContactList()
BindData = New VoucherClass
dt = BindData .Get_Client_List
DataGridView.DataSource = dt
End Sub
Try this: Instead of FrmNewContact.ShowDialog() If FrmNewContact.ShowDialog() = DialogResult.OK Then Me.DataFridView.Refresh() End IF You may need to include a setter for your dialog result at the close action for your modal. Me.DialogResult = DialogResult.OK Me.Close()