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.
Related
My code is as below
Public Class AutoReportForm
Dim con1 = Form1.con1
Dim cmd1, cmd2 As OleDbCommand
Dim adp1, adp2 As OleDbDataAdapter
Dim dtb1, dtb2, dtb3, dtb4, dtb5 As New DataTable
Dim myrpt As New ReportDocument
Dim CrFormatTypeOptions As New PdfRtfWordFormatOptions()
Dim txt As String = Form1.txt
Dim ds As New DataSet()
Sub viewdata()
con1.open()
Dim query As String = "Select * from AUTO_AND_RECIPE where AUTO_BATCH_UNIQUE_CODE = '" + txt + "'"
cmd2 = New OleDbCommand(query, con1)
adp2 = New OleDbDataAdapter(cmd2)
adp2.Fill(dtb2)
cmd1 = New OleDbCommand("Select * from PROCESS where AUTO_BATCH_UNIQUE_CODE_1 = '" + txt + "'", con1)
adp1 = New OleDbDataAdapter(cmd1)
adp1.Fill(dtb1)
con1.Close()
con1.Dispose()
End Sub
Private Sub AutoReportForm_Load(sender As Object, e As EventArgs) Handles Me.Load
dtb1.Clear()
dtb2.Clear()
myrpt.Load("F:\VB2022\SCADAReport\Debug\AutoRpt.rpt")
'TextBox1.Text = txt
viewdata()
myrpt.Database.Tables("AUTO_AND_RECIPE").SetDataSource(dtb2)
myrpt.Database.Tables("PROCESS").SetDataSource(dtb1)
CrystalReportViewer1.ReportSource = Nothing
CrystalReportViewer1.ReportSource = myrpt
End Sub
End Class
This is image of my PROCESS table's datagrid
[This image is showing my crystal report is showing it multiple times][2]
Most likely, you need to add a JOIN condition between the tables.
Without a JOIN condition, every record in Table1 is free to join to every record in Table2.
I am currently writing a simple stock control Visual Basic program linked to a database.
Here's what it looks like so far.
The form displays the data in a DataGrid View and I am trying to refresh my DataGridView automatically when data is changed (using SQL) in the database I am using.
After doing some research I have found that the best way to do this is by binding the data table (using BindingSource) to the DataGridView
However I am struggling to implement this, as every implementation I have tried results in a blank DataGridView and would thoroughly appreciate it if someone could assist me.
Here's the code:
Imports System.Data.OleDb
Public Class Form1
Public connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dbStock.accdb"
Public conn As New OleDb.OleDbConnection(connectionString)
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.TblStockControlTableAdapter.Fill(Me.DbStockDataSet.tblStockControl)
For i As Integer = 1 To 5
ComboBoxQty1.Items.Add(i)
ComboBoxQty2.Items.Add(i)
Next
Dim SqlQuery As String = "Select tblStockControl.[EggType] FROM tblStockControl"
Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "tblStockControl")
Dim dt As DataTable = ds.Tables("tblStockControl")
'DataGridView1.DataSource = dt
For Each row As DataRow In dt.Rows
ComboBoxAdd.Items.Add(row.Item(0))
Next
For Each row As DataRow In dt.Rows
ComboBoxTake.Items.Add(row.Item(0))
Next
End Sub
Private Sub btnAddEgg_Click(sender As Object, e As EventArgs) Handles btnAddEgg.Click
conn.Open()
Dim SqlQuery As String = "Select tblStockControl.[Quantity] FROM tblStockControl WHERE EggType = '" & ComboBoxAdd.Text & "'"
Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "tblStockControl")
Dim dt As DataTable = ds.Tables("tblStockControl")
Dim qty As Integer = 0
For Each row As DataRow In dt.Rows
For Each column As DataColumn In dt.Columns
qty = row(column)
Next
Next
Dim NewQty As Integer = qty + CInt(ComboBoxQty2.Text)
UpdateAddQty(NewQty)
conn.Close()
End Sub
Function UpdateAddQty(ByRef NewQty As Integer) As Integer
Dim SqlUpdate As String = "UPDATE tblStockControl SET Quantity = '" & NewQty & "' WHERE EggType = '" & ComboBoxAdd.Text & "'"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlUpdate
.Connection = conn
.ExecuteNonQuery()
End With
Return (Nothing)
End Function
Private Sub btnViewStock_Click(sender As Object, e As EventArgs) Handles btnViewStock.Click
'Add code to open Access file.
End Sub
Private Sub btnTakeEgg_Click(sender As Object, e As EventArgs) Handles btnTakeEgg.Click
conn.Open()
Dim SqlQuery As String = "Select tblStockControl.[Quantity] FROM tblStockControl WHERE EggType = '" & ComboBoxTake.Text & "'"
Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "tblStockControl")
Dim dt As DataTable = ds.Tables("tblStockControl")
Dim qty As Integer = 0
For Each row As DataRow In dt.Rows
For Each column As DataColumn In dt.Columns
qty = row(column)
Next
Next
Dim NewQty As Integer = CInt(ComboBoxQty1.Text) - qty
UpdateTakeQty(NewQty)
conn.Close()
End Sub
Function UpdateTakeQty(ByRef NewQty As Integer) As Integer
Dim SqlUpdate As String = "UPDATE tblStockControl SET Quantity = '" & NewQty & "' WHERE EggType = '" & ComboBoxTake.Text & "'"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlUpdate
.Connection = conn
.ExecuteNonQuery()
End With
Return (Nothing)
End Function
End Class
If you are using a DataTable , then reset the dataasource of the DataGridView.I mean you need to read data from the database again. :
'Do this every time you add/Update a data
Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "tblStockControl")
Dim dt As DataTable = ds.Tables("tblStockControl")
Or you can just create a row for every data you add to your database :
'Do this every time you add a data
DataGridViewRow row = (DataGridViewRow)DataGridView1.Rows[0].Clone()
row.Cells[0].Value = "Alex"
row.Cells[1].Value = "Jordan"
DataGridView1.Rows.Add(row)
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).
I am having a hard time trying to populate a textbox, and two dropdown lists. What I am attempting to do is this: when the Company dropdownlist has been selected, it will display a grid of its respective values from a sqldatasource, which it does. Now the next step is once a selection from the company dropdown has been made, a textbox will display the membertype as well as the second dropdownlist. The third dropdown displays the groupid. All these three components have their outputs after a selection has been made. But I cannot seem to get the values to show. I also added code for clarification.
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.UI.WebControls
Partial Class companydropdown
Inherits System.Web.UI.Page
Private Sub BindDropDownList(DropdownList1 As DropDownList, query As String, text As String, value As String, defaultText As String)
If Not IsPostBack Then
' Read sql server connection string from web.config file
Dim sConstr As String = ConfigurationManager.ConnectionStrings("ds17701ConnectionString").ConnectionString
Dim Conn As New SqlConnection(sConstr)
Dim dt As New DataTable("tbl")
Using Conn
Conn.Open()
Dim comm As New SqlCommand("SELECT CompanyName,CompanyID FROM CompanyList ORDER BY CompanyName", Conn)
Dim da As New SqlDataAdapter(comm)
'da.Fill(dt)
End Using
'DropdownList1.DataSource = dt
DropdownList1.DataTextField = "CompanyName"
DropdownList1.DataValueField = "CompanyID"
DropdownList1.DataBind()
'DropdownList1.Items.Insert(0, New ListItem("--Select--"))
End If
End Sub
Protected Sub Member_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
If DropDownList1.SelectedIndex > 0 Then
Dim sConstr As String = ConfigurationManager.ConnectionStrings("ds17701ConnectionString").ConnectionString
Dim Conn As New SqlConnection(sConstr)
Dim dt As New DataTable("tbl")
Using Conn
Conn.Open()
Dim comm As New SqlCommand("SELECT CompanyName,CompanyID FROM CompanyList " + DropDownList1.SelectedValue & " ORDER BY CompanyName", Conn)
Dim da As New SqlDataAdapter(comm)
da.Fill(dt)
End Using
'DropDownList2.DataSource = dt
DropDownList2.DataTextField = "MembershipStatus"
DropDownList2.DataValueField = "MemberTypeID"
' Bind sql server data into the Dropdown List
DropDownList2.DataBind()
Else
DropDownList2.Items.Clear()
End If
End Sub
Protected Sub Group_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
If DropDownList1.SelectedIndex > 0 Then
Dim sConstr As String = ConfigurationManager.ConnectionStrings("ds17701ConnectionString").ConnectionString
Dim Conn As New SqlConnection(sConstr)
Dim dt As New DataTable("tbl")
Using Conn
Conn.Open()
Dim comm As New SqlCommand("SELECT CompanyName,CompanyID FROM CompanyList " + DropDownList1.SelectedValue & " ORDER BY CompanyName", Conn)
Dim da As New SqlDataAdapter(comm)
da.Fill(dt)
End Using
'DropDownList2.DataSource = dt
DropDownList3.DataTextField = "GroupID"
DropDownList3.DataValueField = "GroupID"
' Bind sql server data into the Dropdown List
DropDownList3.DataBind()
Else
DropDownList3.Items.Clear()
End If
End Sub
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
DropDownList2.Enabled = False
'DropDownList3.Items.Clear()
DropDownList3.Items.Insert(0, New ListItem("", "0"))
Dim stateId As Integer = Integer.Parse(DropDownList1.SelectedItem.Value)
If stateId > 0 Then
Dim query As String = String.Format("", stateId)
BindDropDownList(DropDownList1, query, "CompanyName", "CompanyId", "")
DropDownList3.Enabled = True
DropDownList2.Enabled = True
End If
End Sub
End Class
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