Datagrid to dbf database using vb.net - vb.net

Datagrid to dbf database updating type of solution couldn't find anywhere, if anybody solve this problem please reply me.
Error - Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
My Code is
Dim con As New OleDbConnection
Dim ds As New DataSet
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
Dim con1 As New OleDbConnection
Dim ds1 As New DataSet
Dim dt1 As New DataTable
Dim da1 As New OleDbDataAdapter
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "Provider=vfpoledb.1;Data Source=C:\dbf_folder;Collating Sequence=machine;"
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from area.dbf", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
da.Fill(dt)
dt.Merge(dt1)
dbfdatagrid.DataSource = dt.DefaultView
con.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
con1.Close()
con1.ConnectionString = "Provider=vfpoledb.1;Data Source=C:\dbf_folder1;Collating Sequence=machine;"
con1.Open()
da1 = New OleDbDataAdapter("Select * from area.dbf", con1)
Dim cb = New OleDbCommandBuilder(da1)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
Dim columns(5) As DataColumn
columns(4) = dt.Columns("NAME")
dt.PrimaryKey = columns
da1.Fill(dt1)
da1.Update(dt)

Looking at your code (I don't know VB, I am more of a C# guy), it is not a matter of VFP, your code is strange given any database.
When the database is VFP, you shouldn't use those QuotePrefix and QuoteSuffix. That by itself, creates a buggy update command. You could also write the update command manually.
Although I don't know VB, doesn't your code create a 6 elements DataColumn array and set only 5th, leaving others as NULL for the primary key? What could be the purpose? Actually you don't need to specify a primary key if you don't have a valid one (then you need to write your update command manually - also it would be your problem if you can build a valid update command to correctly update the rows you need). Let's assume, you go with good database principles and have a primary key in your table. Then you don't need to write manual update, simply have CommandBuilder build it for you. ie:
Sub Main()
Dim tbl As New DataTable()
Dim adapter = New OleDbDataAdapter("select * from Customer", "Provider=VFPOLEDB;Data Source=C:\PROGRAM FILES (X86)\MICROSOFT VISUAL FOXPRO 9\SAMPLES\data")
adapter.Fill(tbl)
Dim cb = New OleDbCommandBuilder(adapter)
adapter.UpdateCommand = cb.GetUpdateCommand()
Dim f = New Form()
Dim btn = New Button With {
.Top = 10,
.Text = "Update"
}
Dim dgv = New DataGridView With {
.Top = 50,
.DataSource = tbl
}
f.Controls.AddRange(New Control() {btn, dgv})
AddHandler btn.Click, Sub(sender, args)
adapter.Update(tbl)
End Sub
f.Show()
End Sub
If you have a table with no primary key that builder could extract from schema, then you could as well write your own manual update code. Just for sampling, assume you have a table in c:\Temp named NoPK (v1 i, v2 c(10)). Although it has no index information and it is a free table (builder cannot determine the PK), we know that v1 is our key and we want to update only v2, could do this:
Sub Main()
Dim tbl As New DataTable()
Dim adapter = New OleDbDataAdapter("select * from NoPK", "Provider=VFPOLEDB;Data Source=c:\Temp")
adapter.Fill(tbl)
adapter.UpdateCommand = New OleDbCommand("update NoPK set v2=? where v1=?", adapter.SelectCommand.Connection)
adapter.UpdateCommand.Parameters.AddWithValue("p1", "").SourceColumn = "v2"
adapter.UpdateCommand.Parameters.AddWithValue("p2", 0).SourceColumn = "v1"
Dim f = New Form()
Dim btn = New Button With {
.Top = 10,
.Text = "Update"
}
Dim dgv = New DataGridView With {
.Top = 50,
.DataSource = tbl
}
f.Controls.AddRange(New Control() {btn, dgv})
AddHandler btn.Click, Sub(sender, args)
adapter.Update(tbl)
End Sub
f.Show()
End Sub
Note that with OleDb, the parameters should be added to the collection in the same order with their corresponding placeholder (?) in command text (IOW you wouldn't add p2 first).

Related

couldnot update datagrid to dbf using vb.net

I am new in programming but learning and research at many time without any course, so i am faced problem at many time. Stack Over flow is right place of solving my issue for me.
This time i have update datagridview to .dbf file for another application where using .dbf database. So Please give me a better solution to prepare my application.
My error is "Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information."
<
My Code is given below.
Dim con As New OleDbConnection
Dim ds As New DataSet
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
Dim con1 As New OleDbConnection
Dim ds1 As New DataSet
Dim dt1 As New DataTable
Dim da1 As New OleDbDataAdapter
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "Provider=vfpoledb.1;Data Source=C:\dbf_folder;Collating Sequence=machine;"
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from voterlist.dbf", con)
da.Fill(dt)
dbfdatagrid.DataSource = dt.DefaultView
con.Close()
End Sub
Private Sub btnupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnupdate.Click
con1.Close()
con1.ConnectionString = "Provider=vfpoledb.1;Data Source=C:\dbf_folder1;Collating Sequence=machine;"
con1.Open()
da1 = New OleDbDataAdapter("Select * from voterlist.dbf", con1)
Dim cb = New OleDbCommandBuilder(da1)
Dim primaryKey(1) As DataColumn
primaryKey(1) = dt1.Columns("areaid")
dt1.PrimaryKey = primaryKey
da1.Fill(dt)
dt.Merge(dt1)
da1.Update(dt)
End Sub
You need to tell the DataSet/DataTable what the primary key is:
' For dataset DS, assumed there is one table
Dim PrimaryKey(1) As DataColumn
PrimaryKey(1) = ds.Tables(0).Columns("ID")
DS.Tables(0).PrimaryKey = PrimaryKey
' For DataTable DT
Dim PrimaryKey(1) As DataColumn
PrimaryKey(1) = dt.Columns("ID")
dt.PrimaryKey = PrimaryKey
Update
You are using the correct driver, you need to create a Unique column in the DBF. To do this execute this SQL on the DBF prior to using it:
ALTER TABLE voterlist ALTER COLUMN areaid INT UNIQUE (I assume an integer column, if character, areaid C(somenumber) where somenumber is the size of the column)
This will create an index on the column areaid which will (should) be used as the primary key.

Dataadapter update with VB

I hope some vb expert could tell me what I am doing wrong.
I am trying to open, modify and update a record in Northwind MDF.
The DA.Update(DS) statement always generate an error.
I find several examples on the net but only in C and thatI dond’t understand, only work in VB. I find myself so stuppid not to understand the update mechanism.
My source:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Call GETNWDS()
ContactNamebox.Text = ContactNamebox.Text + " " + Now
Call UpdateNWDS()
End If
End Sub
Public Sub GETNWDS()
'' open custumor DataAdapter daaset DS
Dim connectionString = ConfigurationManager.ConnectionStrings("NW testConnectionString").ConnectionString
Dim queryString As String = "SELECT CustomerID, CompanyName, ContactName FROM Customers where CustomerID='ALFKI'"
Dim CN As New SqlConnection(connectionString)
Dim DA As SqlDataAdapter = New SqlDataAdapter(queryString, CN)
Dim DS As DataSet = New DataSet
DA.Fill(DS)
Dim DT As DataTable = DS.Tables(0)
Dim row As DataRow = DT(0)
CustomerIDbox.Text = row("CustomerID").ToString
CompanyNamebox.Text = row("CompanyName").ToString
ContactNamebox.Text = row("ContactName").ToString
CN.Close()
End Sub
Public Sub UpdateNWDS()
Dim connectionString = ConfigurationManager.ConnectionStrings("NW testConnectionString").ConnectionString
Dim queryString As String = "SELECT CustomerID, CompanyName, ContactName FROM Customers where CustomerID='ALFKI'"
Dim CN As New SqlConnection(connectionString)
Dim DA As SqlDataAdapter = New SqlDataAdapter(queryString, CN)
Dim DS As DataSet = New DataSet
DA.Fill(DS)
Dim DT As DataTable = DS.Tables(0)
Dim row As DataRow = DT(0)
row("CustomerID") = CustomerIDbox.Text
row("CompanyName") = CompanyNamebox.Text
row("ContactName") = ContactNamebox.Text
Textbox.Text = row("ContactName").ToString
' DA.Update(DS) ' skip to avoud error
CN.Close()
End Sub
The webform is being filled with 3 DB items.
Then 1 box is changed and the update toutineis called but there is an error on the update statement.
Skippimg this statement shows this webform.
Note that the new row value is displalyed in a textbox.

Cannot Add new row to database with DataAdapter.insertCommand vb.net

I try to add new record to the database with command DataAdapter.InsertCommand. But I don't know why It doesn't insert new record to database
Here is my code:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim cnn As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\1_Project\Project_of_VB_Net\AccessDatabase\StudentDatabase.accdb"
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO StudentData(StudentID) VALUES (#studentid)"
cmd.Parameters.AddWithValue("#studentid", "123")
Try
cnn.Open()
da.InsertCommand = cmd
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
cnn.Close()
End Try
End Sub
Please help me find out what's wrong with it?
I'm all in favor of using what works and I see the solution above works. The advantage of using a dataadapter however, is that it wraps all the sql commands needed for the CRUD operations of the datatable. You can configure your own commands or let visual studio configure them automatically by using a sqlcommandbuilder. Then once you have the adapter configured all you need to do is something like this
Dim myds As New DataSet()
Dim mytable as New datatable()
myds.Tables.Add(mytable)
Dim myconstr As String = "ConnectionStringtoDataBase"
Dim myconn As New SqlConnection(myconstr)
Dim da as new SqlDataAdapter( “SELECT * FROM StudentTable”,cnn)
Dim mycb As New SqlCommandBuilder(da)
da.Fill(mytable)
Dim myrow As DataRow = mytable.NewRow()
myrow("ID") = "thestudentid"
myrow("StudentName") = "John doe"
myrow("StudentID") = 12345
myrow("StudentClass") = "VB 101"
mytable.Rows.Add(myrow)
da.Update(mytable)
The CommandBuilder will automatically add insert, update and delete commands to the dataadapter (if your select command is one table only, otherwise you'll have to configure it manually).

Vb.Net: How to execute SQL query inisde datagrid?

I have load a csv file using the code below
Dim fi
Dim conn
Dim adapter1 As New OleDbDataAdapter
Dim ds As New DataSet
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
fi = New FileInfo("C:\path\Book1.csv")
conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName)
conn.Open()
adapter1.SelectCommand = New OleDbCommand("SELECT * FROM " & fi.Name, conn)
adapter1.Fill(ds, "DATA")
DataGridView1.DataSource = ds.Tables(0).DefaultView
End Sub
Now, I want to execute a SQL query like create, select, update, etc inside the gridview. For example, I want to create a new column "test" and fill that column with the values from column "a" and "b". But I get error. Can you please correct the code?
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Try
DataGridView2.Columns.Add("test", "test")
adapter1.SelectCommand = New OleDbCommand("Update Datagridview1 SET test = a + b", conn)
Dim dsA As New DataSet
adapter1.Fill(dsA, "DATA")
DataGridView2.DataSource = dsA.Tables(0).DefaultView
Catch exp As Exception
MsgBox("Error : " & exp.Message)
End Try
End Sub
I cannot test this code now, but usually you change the schema of the DataTable linked to the DataGridView to reflect the new column, and, in your specific case set the Expression property of the newly created column
Dim dv As DataView = CType(DataGridView2.DataSource, DataView)
Dim dc = dv.Table.Columns.Add("test", System.Type.GetType("System.String"))
dc.Expression = "[A] + [B]"
This strongly depends on the datatype of the columns A and B. Here I suppose that they are both strings

Showing all fields in listbox from database, vb.net

I'm trying to make a list box to show all the fields of a particular table in an Access database. I have a few tables, and the idea would be to have each table loaded by a different button (and the items in the box cleared). One trick is that tables aren't all the same size. How do I get all the fields to show up for each table. What I have now is only showing one field:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;data source='C:\dummy_data.accdb';"
Dim conn As New OleDbConnection(connString)
Dim sql As String = "SELECT * FROM Customers"
Dim cmd As New OleDbCommand(sql, conn)
conn.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
ClientList.Items.Clear()
While reader.Read()
ClientList.Items.Add(reader(0).ToString())
End While
reader.Close()
conn.Close()
End Sub
If you are not averse to using a DataGridView instead of a ListView, you could do it this way:
Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;data source='PathToMyDatabase';"
Dim sql As String = "SELECT * FROM Tメイン;"
Dim dt As DataTable
With New OleDbDataAdapter(sql, connString)
Dim ds As New DataSet()
.Fill(ds)
dt = ds.Tables(0)
End With
Me.DataGridView1.DataSource = dt
I do not have 'ACE.OLEDB' on my computer, so had to use the JET provider instead, but it should work the same way.
I should add that you can use this method to retrieve the data from the DB, but there is no easy way as far as I understand to bind a DataTable to a ListView (see this MSDN question for example) and you would have to loop through the columns in your DataTable first and add the column headers to your ListView and then loop through the rows and add the data.
UPDATE:
To answer your questiona s to how to export data from the DataGridView I remembered that I wrote code to do that a little while back.
Private Function ExportToExcelFile(ByVal FileName As String) As Boolean
With New Excel.Application
With .Workbooks.Add()
For Each sheet As Worksheet In .Worksheets
If sheet.Index > 1 Then
Call sheet.Delete()
End If
Next
With CType(.Worksheets(1), Worksheet).Range("A1")
For Each column As DataGridViewColumn In Me.dgvData.Columns
.Offset(0, column.Index).Value = column.HeaderText
For Each row As DataGridViewRow In Me.dgvData.Rows
.Offset(row.Index + 1, column.Index).Value = row.Cells(column.Index).Value
Next
Next
End With
Call .SaveAs(FileName)
End With
Call .Quit()
End With
End Function
I hope this will help to get you started.
Using a Listview control, the following code should do the trick. For simplicity I defined only 4 customer fields - you will need to define them according to your table field defintions:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ClientList.View = View.Details
ClientList.FullRowSelect = True
ClientList.Columns.Add("ID", 120)
ClientList.Columns.Add("Name", 120)
ClientList.Columns.Add("Address", 140)
ClientList.Columns.Add("Email", 100)
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\dummy_data.accdb;"
ClientList.Items.Clear()
Using conn As New Data.OleDb.OleDbConnection(connString)
conn.Open()
Dim sql As String = "SELECT * FROM Customers"
Using cmd As New Data.OleDb.OleDbCommand(sql, conn)
Dim lvi As ListViewItem
Using oRDR As Data.OleDb.OleDbDataReader = cmd.ExecuteReader
While oRDR.Read()
lvi = ClientList.Items.Add(oRDR.GetValue(0).ToString)
For i = 1 To oRDR.FieldCount - 1
lvi.SubItems.Add(oRDR.GetValue(i).ToString)
Next
End While
End Using
End Using
conn.Close()
End Using
End Sub