In the creation of my program, i have found it will be more reliable to supply a local database with the package, rather then connecting to the remote DB for each instance.
Below is my idea on how to do it, however i wish for it to happen automatically for each distinct host that it finds, rather than selecting each member and pressing the button. This is something that i do not know how to achieve.
Imports System.Data.OleDb
Public Class Form1
Dim con as oledbconnection = new oledbconnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='.\localDB.accdb'")
Dim rem as oledbconnection = new oledbconnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='\\server\remote.accdb'")
dim da as new oledbdataadaptor
dim dt as new datatable
dim dt2 as new datatable
Dim Str as string
Dim cmd as new oledbcommand(str, con)
Private Sub Form1_load
con.open()
da.SelectCommand = New OleDbCommand("select distinct Host from Logs")
da.fill(dt)
con.close
Combobox1.datasource = dt
Combobox1.displaymember = "Host"
End Sub
Private Sub button1_click
con.open()
Dim cmd As New OleDbCommand("select * from local where host=#host;", con)
cmd.parameters.addwithvalue("#host", combobox1.text.tostring)
da.fill(dt2)
con.close()
rem.open()
Dim cmd1 As New OleDbCommand("update remote set col1=#col1 where ID=#ID;", con)
cmd1.parameters.addwithvalue("#col1", dt2.rows(0).item(1).tostring)
cmd1.parameters.addwithvalue("#ID", dt2.rows(0).item(0).tostring)
rem.close()
End Sub
End Class
Any idea's would be appreciated.
*As a note, i realise that JET offers the sync ability however the database is required to be in the 2007-10 format, so ACE is the only option.
First of all OleDbCommand does not accept named parameters, so you need to reference them with ? and pass the parameters in the same order that they appear.
Dim cmd As New OleDbCommand("select * from local where host = ?", con)
cmd.parameters.Add(combobox1.Text.ToString)
Once done, you'll need to fill the DataSet with the results of the SQL sentence
Dim DA As New OleDbDataAdapter(cmd)
Dim DS As New DataSet
DA.Fill(DS, "hosts")
UPDATE
In order to have an equivalent code as yours, I would do something like this
Imports System.Data.OleDb
Public Class Form1
Dim con as oledbconnection = new oledbconnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='.\localDB.accdb'")
Dim rem as oledbconnection = new oledbconnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='\\server\remote.accdb'")
dim dt as New DataTable
Dim Str as String
Dim cmd as New OleDbCommand(str, con)
Private Sub Form1_load
con.open()
da.SelectCommand = New OleDbCommand("select distinct Host from Logs")
da.fill(dt)
con.close
For Each DR as DataRow In DT.Rows
con.open()
Dim cmd As New OleDbCommand("select * from local where host= ? ", con)
cmd.Parameters.Add(DR.Item(0))
Dim DA As New SqlClient.SqlDataAdapter(cmd)
Dim DS As New DataSet
da.Fill(DS,"hosts")
con.close()
rem.open()
Dim cmd As New OleDbCommand("update remote set col1=? where ID=?", rem)
cmd.Parameters.Add(DS.Tables("hosts").Rows(0).Item(1).ToString)
cmd.Parameters.Add(DS.Tables("hosts").Rows(0).Item(0).ToString)
cmd.ExecuteNonQuery()
rem.close()
Next
End Sub
End Class
Related
Hello there I am quite new to windows form programming, and my project requires me to do a search query on my database. I would like the option for the names that can be currently searched to be displayed when typing, however, after pressing the search button the autocomplete no longer displays when I try to look for another attribute. https://i.stack.imgur.com/Wytdy.png , https://i.stack.imgur.com/Qjy5q.png
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(mSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customers")
dt = ds.Tables(0)
MaxRows = ds.Tables("customers").Rows.Count
con.Close()
Dim msSQL As String = "SELECT * FROM customers;"
dgvCustomerInfo.DataSource = display(msSQL, "customers")
Try
dt = New DataTable
con.Open()
With cmd
.Connection = con
.CommandText = "SELECT DISTINCT fname FROM customers"
End With
da.SelectCommand = cmd
da.Fill(dt)
Dim r As DataRow
txtSearchName.AutoCompleteCustomSource.Clear()
For Each r In dt.Rows
txtSearchName.AutoCompleteCustomSource.Add(r.Item(0).ToString)
Next
''''''''''''''''''''''''
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
da.Dispose()
I believe your problems stem from the AutoCompleteMode. Suggest and SuggestAppend seem to fill in the text box as expected. Append seem to do nothing. I don't think this is working as intended.
I tested with a little database I have. It is Sql Server but should work the same for Sqlite. I used a bit of Linq magic to get the AutoCompleteCustomSource. A few other changes... Using...End Using blocks ensure that database objects are closed and disposed. You don't need a DataAdapter, just a DataTable and Command.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetDataForTextBox()
Dim strArray = dt.AsEnumerable().[Select](Function(x) x.Field(Of String)("Name")).ToArray()
TextBox5.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim MySource As New AutoCompleteStringCollection()
MySource.AddRange(strArray)
TextBox5.AutoCompleteCustomSource = MySource
TextBox5.AutoCompleteMode = AutoCompleteMode.SuggestAppend
End Sub
Private Function GetDataForTextBox() As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select Distinct Name From Coffees", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = GetSearchResults(TextBox5.Text)
DataGridView1.DataSource = dt
End Sub
Private Function GetSearchResults(name As String) As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select * From Coffees Where Name = #Name", cn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = name
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
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).
I know that this is a duplicate post but I couldn't find my solution on that topics. I want to connect my sql file in debug folder but I got error that Login failed for user ''.
Dim connectionString As String = String.Format("Data Source=.\SQLEXPRESS;AttachDbFilename={0}\Word.mdf;Integrated Security=False;Connect Timeout=30;User Instance=True", My.Application.Info.DirectoryPath)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sql As String = "SELECT * FROM test"
Dim connection As New SqlConnection(connectionString)
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "test_table")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "test_table"
MakePivot()
connection.Close()
DataGridView2.ClearSelection()
End Sub
Could you tell me my mistake please?
Dim ds As New DataSet()
Using connection As New SqlConnection(String.Format("Data Source=.\SQLEXPRESS;AttachDbFilename={0}\Word.mdf;Integrated Security=true;Connect Timeout=30;User Instance=True", My.Application.Info.DirectoryPath))
connection.Open()
Using command As New SqlCommand("SELECT * FROM test", connection)
command.CommandTimeout = 0
Using da As New SqlDataAdapter(command)
da.Fill(ds)
End Using
End Using
End Using
DataGridView1.DataSource = ds
MakePivot()
DataGridView2.ClearSelection()
Try this code, need to set "integrated security=true"
I am trying to get the datagridview data to Crystal report, but i am getting this ERROR message "Input array is longer than the number of columns in this table."
Any Idea how to fix my error?
Sub PrintToCR()
Dim dt As New DataTable
For Each dr As DataGridViewRow In Me.DataGridView1.Rows
dt.Rows.Add(dr.Cells("ProductID").Value, dr.Cells("BrandName").Value, dr.Cells("GenericName").Value, _
dr.Cells("ExpirationDate").Value, dr.Cells("Price").Value, _
dr.Cells("Unit").Value, dr.Cells("QuantityOnHand").Value) '<<<<< Error is HERE.
Next
'
Dim rptDoc As CrystalDecisions.CrystalReports.Engine.ReportDocument
rptDoc = New CrystalReport1
rptDoc.SetDataSource(dt)
'
CrystalReportViewer.CrystalReportViewer1.ReportSource = rptDoc
CrystalReportViewer.ShowDialog()
CrystalReportViewer.Dispose()
End Sub
this is my Database transaction
Public Class data
Dim connString As New connection
Dim con As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Public Function List(ByVal sql As String) As DataSet
con.ConnectionString = connString.connectionString
con.Open()
da = New OleDb.OleDbDataAdapter(sql, con)
Dim ds As New DataSet
da.Fill(ds, "data")
con.Close()
List = ds
End Function
Public Sub ExecuteSql(ByVal sql As String)
con.ConnectionString = connString.connectionString
con.Open()
cmd.CommandText = sql
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.ExecuteNonQuery()
con.Close()
End Sub
End Class
Btw, my Datagridview is connected via Datasource
thanks
try this ..
Dim dt As New DataTable
dt.Columns.Add("ProductId")
dt.Columns.Add("BrandName")
dt.Columns.Add("GenericName")
dt.Columns.Add("ExpirationDate")
dt.Columns.Add("Price")
dt.Columns.Add("Unit")
dt.Columns.Add("QuantityOnHand")
For Each dr As DataGridViewRow In Me.DataGridView1.Rows()
dt.Rows.Add(dr.Cells("ProductID").Value, dr.Cells("BrandName").Value, dr.Cells("GenericName").Value, _
dr.Cells("ExpirationDate").Value, dr.Cells("Price").Value, _
dr.Cells("Unit").Value, dr.Cells("QuantityOnHand").Value)
Next
'
Dim rptDoc As CrystalDecisions.CrystalReports.Engine.ReportDocument
rptDoc = New CrystalReport1
rptDoc.SetDataSource(dt)
CrystalReportViewer.CrystalReportViewer1.ReportSource = rptDoc
CrystalReportViewer.ShowDialog()
CrystalReportViewer.Dispose()
I have a gridview in which I am assigning the dataset as datasource in my program.
My Form_Load() event is:
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim cn As New SqlConnection("Data Source=HCL-43AF369E5A0;Initial Catalog=Exam;Integrated Security=True")
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds As DataSet
cn.Open()
cmd = New SqlCommand("Select * from Contact", cn)
da = New SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds)
cn.Close()
DataGridView1.DataSource = ds
End Sub
What is the error in my code? I have debugged the code and found that the dataset fetches the data but not able to bind it to gridview.
Please help.
You have to assign a Datatable as DataGridView1.DataSource. Not the DataSet. Use ds.Tables() property.
formal ways is
Dim cn As New SqlConnection("Data Source=HCL-43AF369E5A0;Initial Catalog=Exam;Integrated Security=True")
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds As DataSet
cn.Open()
cmd = New SqlCommand("Select * from Contact", cn)
da = New SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds) // edit here like da.fill(ds, "table name")
cn.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "table name"
// table name will be any not the same as in your database
Your dataset is actually a data which you get by executing your query like "select * from tablename"
even you can have more than one table in a dataset so its formal method to give datamember name.