Update database table from DataGridView using DataAdapter - vb.net

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)?

Related

SELECTing data from database in vb and outputting data into label

I have the following code which SELECTs data from a database and outputs a value to a label on the form:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim strConn As String = System.Configuration.ConfigurationManager.ConnectionStrings("yourConnectionString").ToString()
Dim sql As String = "SELECT aid FROM tbl_RAPA WHERE username=#username"
Dim conn As New Data.SqlClient.SqlConnection(strConn)
Dim objDR As Data.SqlClient.SqlDataReader
Dim Cmd As New Data.SqlClient.SqlCommand(sql, conn)
Cmd.Parameters.AddWithValue("#username", User.Identity.Name)
conn.Open()
objDR = Cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
While objDR.Read()
Label1.Text = objDR("aid")
End While
End Sub
However, if the value in the database is empty, the program runs into an error. Is there a way for me to do this so the program just returns an empty value rather than crashing?
The error message i am given is System.InvalidCastException: 'Unable to cast object of type 'System.DBNull' to type 'System.Windows.Forms.Label'.' on the line Label1.Text = objDR("aid")
Database objects generally need to be closed and disposed. Using...End Using blocks will do this for you even if there is an error.
Since you are only expecting one piece of data you can use .ExecuteScalar which provides the first column of the first row of the result set. This method returns an object.
Try to always use the the .Add method with Parameters. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
Here is another
https://andrevdm.blogspot.com/2010/12/parameterised-queriesdont-use.html
I had to guess at the database type so, check your database for the real value.
Don't update the User Interface until after the connection is closed and diposed. (End Using). I declared aid before the Using block so, it could be used after the block. Check if the object, aid, is not Nothing before adding it to the label's Text.
Imports MySql.Data.MySqlClient
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim aid As Object
Using conn As New MySqlConnection(ConfigurationManager.ConnectionStrings("yourConnectionString").ToString),
cmd As New MySqlCommand("SELECT aid FROM tbl_RAPA WHERE username=#username", conn)
cmd.Parameters.Add("#username", MySqlDbType.VarChar).Value = User.Identity.Name
aid = cmd.ExecuteScalar
conn.Open()
End Using
If Not IsNothing(aid) Then
Label1.Text = aid.ToString
End If
End Sub
I would add this before While objDR.Read() as a precaution in case your query returns no rows:
if objDR.HasRows
...
Then, to handle the null values (this is probably what you mean by empty):
If Not String.IsNullOrEmpty(objDR.Item("aid")) Then
Label1.Text = objDR("aid")
Else
Label1.Text = "Null !"
End if
You could also use ExecuteScalar() if you are only expecting one record. But you would need to handle the situation where no matching record is found.

Add column to SQL table and populate to datagridview

I have a windows form application with databound datagridview. I want to add column at run time (if user wants to add more column to it). So on button click I wanted to add column. I have added following code to event it adds column in server explorer view under tables column's list but does not show in table definition neither in data source window (in column list under table) nor in datagridview.
Imports System.Configuration
Imports System.Data.SqlClient
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Small_databaseDataSet.newtable' table. You can move, or remove it, as needed.
Me.NewtableTableAdapter.Fill(Me.Small_databaseDataSet.newtable)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddColumn()
End Sub
Private Sub AddColumn()
Dim connString As String = "Data Source=(localDb)\ProjectsV13;Initial Catalog=small database;Integrated Security=True"
Dim dt As New DataTable
Using conn As New SqlConnection(connString)
Dim str As String = "ALTER TABLE newtable ADD " & TextBoxX1.Text & " INT null;"
Using comm As New SqlCommand(str, conn)
conn.Open()
comm.ExecuteNonQuery()
End Using
End Using
Validate()
DataGridViewX1.Columns.Clear()
NewtableTableAdapter.Update(Small_databaseDataSet.newtable)
NewtableTableAdapter.Fill(Small_databaseDataSet.newtable)
DataGridViewX1.DataSource = NewtableBindingSource
End Sub
End Class
Change this line of code:
' Add the keyword NULL and brackets around the column name
Dim comm As New SqlCommand("ALTER TABLE testTable ADD [col1] INT NULL", conn)
If I wanted to have the new column to show up automatically, I would re-query the database, retrieving the data on that table and just set the datagridview datasource to the resultset like:
'I assume the datagridview name is DataGridView1
DataGridView1.Columns.Clear()
DataGridView1.DataSource = USTDatabaseDataSet
DataGridView1.DataMember = "testTable"
DataGridView1.DataBind()
A DataReader is used to retrieve data. Since there is no data retrieved nothing is loaded into your DataTable except maybe a return value of success or failure. The Using statements ensure that your objects are closed and disposed properly even if there is an error.
Private Sub AddColumn()
Dim connString As String = ConfigurationManager.ConnectionStrings("USTDatabaseConnectionString").ConnectionString
Dim dt As New DataTable
Using conn As New SqlConnection(connString)
Using comm As New SqlCommand("ALTER TABLE testTable ADD col1 INT;", conn)
conn.Open()
comm.ExecuteNonQuery()
End Using
Using com2 As New SqlCommand("Select * From testTable;", conn)
Using reader As SqlDataReader = com2.ExecuteReader
dt.Load(reader)
conn.Close()
End Using
End Using
End Using
DataGridView1.DataSource = dt
End Sub

Changes in Datagridview not saving in table SQLite 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.

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 edit/delete records in a datagridview?

I'm using this code for the deleting of records in a datagridview using VB.NET and SQL -12
Private Sub Delete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Delete.Click
If MessageBox.Show("delete this item?", "DELETE!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then
Me.DataGridView.Rows.RemoveAt(Me.DataGridView.CurrentRow.)
Else
DataGridView.Update()
End If
End Sub
When I'm using this, the record only gets deleted temporarily but not permanently from the database. How should I delete the records permanently?
The same is the case when I'm editing a field. It's just temporary.
Then you set the deletecommand for the sqldataadapter. The code depends on your table's KeyID name and type, among other things.
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter = New SqlDataAdapter()
...
(here you wrote the dataadapter Fill code)
...
Dim cmdDelete As New SqlCommand("DELETE FROM Customers WHERE KeyID = #KeyID", connection)
cmdDelete.Parameters.Add("#KeyID", SqlDbType.NChar, 8, "KeyID")
adapter.DeleteCommand = command
I think the dataadapter wizard should have done this for you though.