How to determine the id of a data in vb.net? - vb.net

I'm currently working on an ms access database in vb.net.
And I need a code that can determine which data I am updating in the database. Because when I try to update the data, the previous data is being cloned and it will generate two data(the updated and the previous data), and the program will also generate a random id number for the updated data, which is not good.
Here is my code for the update button:
'update
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("GH").Rows(INC).Item(1) = TextBox13.Text
ds.Tables("GH").Rows(INC).Item(2) = TextBox14.Text
ds.Tables("GH").Rows(INC).Item(3) = TextBox15.Text
da.Update(ds, "GH")
MsgBox("Data updated")
My code for form load:
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\ACCESS DATABASE\search.mdb"
con.Open()
sql = "SELECT * FROM GH"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "GH")
con.Close()
I'm using system.data.oledb namespace
Here are my declarations:
Dim cmd As OleDbCommand
Dim cn As OleDbConnection
Dim dr As OleDbDataReader
Dim ds As New DataSet
Dim con As New OleDb.OleDbConnection
Dim da As OleDb.OleDbDataAdapter

Your question is not clear to me at all, but if you want to find the last ID of an insert, you would usually check the results of "SELECT ##IDENTITY" immediately after the record is inserted.

Related

DataSet update error requires InsertCommand

Trying to add a row to an Access 2010 database with VB 2013. Everything seems to work until the UPDATE statement when I get this error:
Update requires a valid InsertCommand when passed DataRow collection with new rows.
My code is:
Dim sqlConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\CLI_CRVM.accdb")
Dim cmd As New System.Data.OleDb.OleDbCommand()
Dim ds As New DataSet1()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "SELECT * FROM [extract] ;"
cmd.Connection = sqlConnection
sqlConnection.Open()
Dim da = New OleDb.OleDbDataAdapter(cmd.CommandText, sqlConnection)
da.Fill(ds, "extract")
ds.Clear()
Dim newExtractRow As DataRow = ds.Tables("extract").NewRow()
newExtractRow("Field1") = "ABC123"
ds.Tables("Extract").Rows.Add(newExtractRow)
da.Update(ds, "Extract")
sqlConnection.Close()
Everything I've found so far seems to reference an SQL database, not OleDb connection.
You can probably use an OleDbCommandBuilder, like so
' your existing OleDbDataAdapter
Dim da = New OleDb.OleDbDataAdapter(cmd.CommandText, sqlConnection)
' add the following lines:
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
For details, see
OleDbCommandBuilder Class
Working Example
For an Access table named extract with fields
ID - AutoNumber, Primary Key
Field1 - Text(255)
and data
ID Field1
-- -------
1 TEST999
the following VB.NET code will insert a second row into the table in the Access database
Using con As New OleDbConnection
con.ConnectionString =
"Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=C:\Users\Public\Database1.accdb;"
con.Open()
Using da As New OleDbDataAdapter("SELECT * FROM [extract]", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
Dim dt = New DataTable
da.Fill(dt)
Dim dr As DataRow = dt.NewRow
dr("Field1") = "ABC123"
dt.Rows.Add(dr)
da.Update(dt)
End Using
con.Close()
End Using
with the result
ID Field1
-- -------
1 TEST999
2 ABC123
The OleDbCommandBuilder object automatically (and invisibly) creates the INSERT, UPDATE, and DELETE commands based on the SELECT command that was supplied when the OleDbDataAdapter object was created.
You need to set the InsertCommand property
Dim da = New OleDb.OleDbDataAdapter(cmd.CommandText, sqlConnection)
da.InsertCommand = cmd
da.Fill(ds, "extract")
More info here

VB.net | how can i turn an access db record in to a tabcontrol add tabpage?

I have a question, I want to add a TabPage to my TabControl from an access record? I think it's something along these lines but it didn't work:
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\data\testing.Accdb;Persist Security Info=False;")
con.Open()
Dim constr As String = "SELECT ProductType, Discription FROM TblProductType"
Dim cmd As OleDbCommand = New OleDbCommand(constr, con)
Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim ds As DataSet = New DataSet()
da.Fill(ds, "TblProductType")
Me.TabControl1.TabPages.Add("Discription")
con.Close()
You have to iterate over the row collection of the table:
Using cmd As New OleDbCommand("SELECT ProductType, Discription FROM TblProductType", con)
Using rdr As OleDbDataReader = cmd.ExecuteReader
While rdr.Read
TabControl1.TabPages.Add(rdr("Discription").ToString)
End While
End Using
End Using
Of course, this only gives you an empty TabPage for every record and in it's current implementation, you don't have any reference to the record anymore. That ProductType, if it's unique, should be used somewhere, too.

Update Access database records by column, row known

This is what I've got so far :
Dim myCONN As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\Baza.mdb")
Dim cmd1 = New OleDbCommand("SELECT ID FROM Baza WHERE NAZIV=#XXNAZIV")
cmd1.Parameters.AddWithValue("#XXNAZIV", TextBox2.Text)
cmd1.Connection = myCONN
myCONN.Open()
Dim result = cmd1.ExecuteReader()
While (result.Read())
Dim rowx As Integer = GetTextOrEmpty(result("ID"))
End While
I've found the row (rowx) in which I would like to change values in 20 corresponding columns (namesID : NAZIV, SIFRA,...). Data is already presented in textboxes (textbox1...), but I don't know how to finish this code with UPDATE and how to insert changed values back to Access.
Dim cmdText As String = "UPDATE Baza SET NAZIV=#XXNAZIV Where ID=SomeId"
Using con = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = h:\Baza.mdb")
Using cmd = new OleDbCommand(cmdText, con)
con.Open()
cmd.Parameters.AddWithValue("#XXNAZIV",TextBox2.Text)
cmd.ExecuteNonQuery()
End Using
End Using
This should help you to solve your problem, of course you will have to pass ID parameter to query also.
Reference

Populating and editing datagrid from a SQL Server table

I need to populate my datagrid from my a table in SQL Server called Pastel_Companies and then if any changes are made to the datagrid it has to update it to the database.
I am using a default view to populate my datagrid.
Is there another way where I link each column separately so I can resize my columns as they are fixed to what SQL has?
Here is my code:
Dim cn As New SqlClient.SqlConnection(SQL_Loader("", My.Settings.SQL_Win_Auth, My.Settings.SQL_Username, My.Settings.SQL_Password, My.Settings.SQL_Server_Name, My.Settings.SQL_DB_Name))
Dim Cmd As New SqlClient.SqlCommand
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New SqlClient.SqlDataAdapter
Cmd.Connection = cn
cn.Open()
da = New SqlClient.SqlDataAdapter("Select Company_ID, Prefix, DSN, File_Path From Pastel_Companies", cn)
da.Fill(dt)
'DataGridView1.Columns.Add("Company_ID", Prefix.ToString)
DataGridView1.DataSource = dt.DefaultView
cn.Close()
From: http://social.msdn.microsoft.com/Forums/windows/en-US/e444ca84-3319-4dfa-aa31-46f310dd0c13/datagridview-autosize-rowcolumn
'for the rows
DataGridView1.AutoResizeRow(2, DataGridViewAutoSizeRowMode.AllCellsExceptHeader)
'and for columns
DataGridView1.Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
or you can use for each loop
DataGridView1.Columns(i).Width = x

Retrieving rows from a MS Access Database View using Vb.Net

I've managed to get the following code...
con.ConnectionString = My.Settings.dbConnection
Dim sqlCmd As System.Data.OleDb.OleDbCommand = New System.Data.OleDb.OleDbCommand()
con.Open()
sqlCmd.Connection = con
Dim schemaTable As DataTable
schemaTable = con.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Views, Nothing)
To retrieve a list of Views in my Access database, but now I want to retrieve the results based on a selected View.
Is there a correct method in doing this, or do I take the SQL Statement from the DataTable returned for each row?
Suppose you have Query1 (View) in your Access database (Database1.accdb file). The following code will output each row of the query to the console (for demo purposes):
Dim con As OleDbConnection = New OleDbConnection()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Database1.accdb;Persist Security Info=False;"
Dim sqlCmd As OleDbCommand = New System.Data.OleDb.OleDbCommand()
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.CommandText = "Query1"
sqlCmd.Connection = con
con.Open()
Dim reader As OleDbDataReader
reader = sqlCmd.ExecuteReader()
If reader.HasRows Then
While reader.Read()
Console.WriteLine(reader("Column1")) 'output specific column
End While
End If
Console.ReadLine()
Hope this helps