How to load data from an SQLite Database query into a textbox? - sql

So I'm making a rota system for a project and I need a textbox to output the contracted hours of the employee that the user currently has selected in the combo box. The problem is, I have no idea how to go about it;
Sub GetContractedHours()
Dim sSql As String
Dim newds As New DataSet
Dim newdt As New DataTable
sSql = "SELECT emp_contractedhours FROM Employee WHERE emp_fn ='" & cboEmpName.Text & "%'"
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(sSql, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(newds, "Employee")
newdt = newds.Tables(0)
txtUserAlertHours.DataSource = newdt
con.Close()
End Sub
Please help! :)

You don't need any of that code. Just get all the data in the first place and then bind your ComboBox and your TextBox, e.g.
Dim table As New DataTable
Dim conection As New SQLiteConnection(ConnectionString)
Dim adapter As New SQLiteDataAdapter("SELECT emp_fn, emp_contractedhours FROM Employee", connection)
adapter.Fill(table)
cboEmpName.DisplayMember = "emp_fn"
cboEmpName.DataSource = table
txtUserAlertHours.DataBindings.Add("Text", table, "emp_contractedhours")
The TextBox will then be automatically populated when you make a selection in the ComboBox. That's how data-binding works.
If you do want to query the database each time then you shouldn't use a data adapter at all. You're only retrieving one value and that's exactly what ExecuteScalar is for. Create a command with the appropriate SQL, call ExecuteScalar and assign the result to the Text of your TextBox.
If you really did want to use data-binding with the code you have (which would be silly) then you can bind just as I have demonstrated above. Just note that, if you're going to use a different DataTable each time, you need to remove the old binding first. You can do that most easily by calling Clear on the DataBindings collection, assuming you have not bound any other properties.

Related

Datagridview how to fill data from another datagridview

in my invoicing software I have the "master" datagridview which I integrated with a lookup feature: once user presses F3 while on the Code field, it shows a modal form with another datagridview that shows a list of products to choose from.
Where i'm stuck is where user clicks Ok on the selected products, because I don't know well how to fill the Datagridview correctly in order to have all on the same row. Here's my code:
Private Function RicercaxCodiceArticolo(ByVal codiceart As String)
Dim strsql As String
Dim cmd As SqlCommand
Dim source As New BindingSource
Dim count As Integer
connection.Open()
strsql = "SELECT CODICEARTICOLO AS 'Codice', DESCRIZIONEARTICOLO AS 'Descrizione', UNITAMISURA AS 'Um', CODICEIVA AS 'Iva' " _
& ",COSTOBASE AS 'Costo', PREZZOBASE AS 'Prezzo', COSTOULTIMO AS 'Costo Ult.', BARCODE AS 'Barcode', NOTEARTICOLO AS 'Note' " _
& ",CATEGORIAARTICOLO AS 'Categ.Art.', GIACENZA AS 'Giacenza', FORNITOREPREF AS 'Fornit. Pref.' FROM Articoli " _
& " WHERE CODICEARTICOLO = '" & codiceart & "'"
cmd = New SqlCommand()
cmd.CommandText = strsql
cmd.CommandType = CommandType.Text
cmd.Connection = connection
'TODO: Completare
source.DataSource = cmd.ExecuteReader
DataGridView1.Rows.Add(source.Current!Codice)
DataGridView1.Rows.Add(source.Current!Descrizione)
connection.Close()
End Function
Of course the second line of the Add method is wrong, but how do I fill all the data on the same line?
Well … I will assume a couple of things that you are neglecting to tell us.
We must assume that the first grid does NOT use a DataSource and the columns are added in the designer or in some code you are not showing. This assumption is based on the code that adds the rows directly to the grid since you can not add rows directly to the grid when it is data bound.
Also, I will assume that the line of code …
source.DataSource = cmd.ExecuteReader
… is returning a DataTable from the SQL command cmd.
If both my assumptions are correct, then in my small tests, the line of code…
source.Current
Will return a DataRowView object of the “selected” row in source and you simply need to cast it to a DataRowView to get the values you want to add to the single row in the grid. Something like…
Dim drv As DataRowView
drv = CType(source.Current, DataRowView)
DataGridView1.Rows.Add(drv("Codice"), drv("Descrizione"))
Lastly, it may be a better approach to use a DataTable as a DataSource for the first grid's BindingSource and simply "Import" the row into the DataTable. Pick your own poison.

Visual Studio - multiple Table to multiple DataGridView with MS Access

how can i populate multiple table into multiple DataGridview?
for example i have 3 tables which is table1, table2 and table3, and in my form i have 3 dataGridView with name of dataGridView1, dataGridView2 and dataGridView3. i found this solution Updating an Access Database via a DataGridView Using OLEDB in VB.NET as a result of my code.
function loadDatabaseDataToGridView
Dim msAccessFilePath As String
Dim con As New OleDbConnection
Dim dataTable, dataTable2, dataTable3, dataTable4 As New DataTable
Dim olebDataAdapter As New OleDbDataAdapter
Dim da As New OleDbDataAdapter
Dim dataSet As New DataSet
Private Sub loadDatabaseDataToGridView()
Try
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & msAccessFilePath
dataSet.Tables.Add(dataTable)
olebDataAdapter = New OleDbDataAdapter("Select * from table1", con)
olebDataAdapter.Fill(dataTable)
olebDataAdapter = New OleDbDataAdapter("Select * from table2", con)
olebDataAdapter.Fill(dataTable2)
olebDataAdapter = New OleDbDataAdapter("Select * from table3", con)
olebDataAdapter.Fill(dataTable3)
DataGridView1.DataSource = dataTable.DefaultView
DataGridView2.DataSource = dataTable2.DefaultView
DataGridView3.DataSource = dataTable3.DefaultView
Dim cb = New OleDbCommandBuilder(olebDataAdapter)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
MessageBox.Show("Successfull")
Catch ex As Exception
MessageBox.Show("Failed")
con.Close()
End Try
con.Close()
End Sub
function SaveChanges
'Perform this on Button Save is Click
Private Sub saveChanges()
olebDataAdapter.Update(dataSet)
End Sub
This code is working as excpected, it is populating the data from MS Access file but when i clicked the button save to save the changes on edited data, an error has occurred.
THE ERROR:
Concurrency violation: the UpdateCommand affected 0 of the expected 1 records
anyone does know how to properly implement of what i am trying to achieve? Thank You Very Much!!!
Each DataAdapter object only has a single UpdateCommand, so you'll need one for each data table. If it runs the update command and no rows are updated (because the update command is actually for a table that you haven't changed) then you'll get the Concurrency Violatation.
It actually gets more complicated than this if your tables are related as the order that inserts, updates and deletions occur can be critical.
If you create a Strongly Typed Dataset it generates designer code that includes a TableAdapterManager class and all of the required data adapters. It might be worth playing around with this just so that you can see how the generated code works.
Just a note, the 'Concurrency violation' exception is actually there so that you can design an update command that will only succeed if the contents of the record in the database match the data held locally (to prevent you from overwriting another user's changes). Search for Optimistic Locking for more details.

Populate column values from MS Access database into VB .Net Combo-Box dropdown values?

I am accessing data from Access MDB file using my application developed in VB .net 2010.
I want to get values from a particular table-column to be populated in a Combo Box dropdown.
I followed a similar thread # C# Adding data to combo-box from MS Access table but as the code is in C#, I was not able to successfully implement it. And reverted back to my previous code.
Because the Table will be updated by another application as well, every time I use my utility I need to get the latest data from that table. Hence I would like to have a feature that could get all available id from table.
Below is what I have been trying to do..
'below declared at class level.
' Dim cnnOLEDB As New OleDbConnection
' Dim cmdOLEDB As New OleDbCommand
cnnOLEDB.Open()
cmdOLEDB.CommandText = "select unique_id from tag_data"
cmdOLEDB.Connection = cnnOLEDB
Dim rdrOLEDB2 As OleDbDataReader = cmdOLEDB.ExecuteReader
If rdrOLEDB2.Read = True Then
TagComboBox1.DataSource = rdrOLEDB2.Item(0).ToString
TagComboBox1.ValueMember = "unique_id"
TagComboBox1.DisplayMember = "unique_id"
End If
rdrOLEDB2.Dispose()
rdrOLEDB2.Close()
cnnOLEDB.Close()
I would recommend filling a DataTable with your query. Then you can set the DataSource of the combobox, ValueMember & the DisplayMember.
Dim dt As New DataTable
Dim query As String = "select unique_id from tag_data"
Using connection As New OleDbConnection("your connection string")
Using command As New OleDbCommand(query, connection)
Using adapter As New OleDbDataAdapter(command)
connection.Open()
adapter.Fill(dt)
connection.Close()
End Using
End Using
End Using
If dt.Rows.Count > 0 Then
TagComboBox1.DataSource = dt
TagComboBox1.ValueMember = "unique_id"
TagComboBox1.DisplayMember = "unique_id"
End If

Query/Update MS Access Records

I am attempting to populate items into a datagrid and then update them back into the database using 2 buttons (one loads, one will save) and a datagrid on a form. I keep running into "Syntax error (missing operator) in query expression" upon update and I am not sure why. Another question i have is where do my DataAdapter and Dataset need to be dimensioned in memory? Under the class?
'this loads my data from db into datagrid
Dim con As New OleDb.OleDbConnection
Dim sql As String
con.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;data source=dbsrc.mdb"
con.Open()
sql = "SELECT * from [Employee Assignments]"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Assignments")
con.Close()
DataGridView1.DataSource = ds.Tables("Assignments")
The following code should update my database to reflect changes made in the datagridview
'this will eventually update the datagrid back into the db
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim con As New OleDb.OleDbConnection
'Dim sql As String
con.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;data source=dbsrc.mdb"
con.Open()
da.Update(ds, "Assignments")
con.Close()
DataGridView1.DataSource = ds.Tables("Assignments")
I read this artcle on msdn - http://msdn.microsoft.com/en-us/library/system.data.common.dataadapter.update.aspx - but it did not seem to help much, I am confused but I believe my problem is not identifying and passing the correct dataset back into the database. How should I deal with the dataset that I pull, modify, and then send back into the DB using the DataAdapter?
When a table contains spaces in its name you should inform the CommandBuilder about this problem
setting the QuotePrefix and QuoteSuffix property to avoid errors
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
The default for these twos is an empty string and thus, when you try to write your changes back to the database, you get a syntax error.

Populate data from dataset and show in datagridview

I am working in VB.NET and I have a simple requirement:
I have added a MDB file to a DataSet and it contains 21 tables.
I have a DataGridView and a ComboBox on my form.
I was able to get the ComboBox populated with the table names available in the DataSet by iterating through dataset.Tables.
Now I want to the user to be able to select the table name from the ComboBox and then populate the contents of that table.
I tried the following code:
Datagridview1.DataSource = dataset1
Datagridview1.DataMember = dataset1.tables(combobox1.selecteditem)
Datagridview1.Refresh()
But I only got the column headers. Then I read that I need a TableAdapter to populate the DataSet with that table. But if I use the TableAdapter then I won't be able to populate the table in a generic way.
Currently if I have to populate TableA then I will have to create an instance of Dataset1TableAdapters.TableA and then use it's .Fill property to populate the table. I will also have to use "Dataset1TableAdapters.TableB`. Is there a generic method to populate any table in the DataSet?
The following worked for me:
Datagridview1.DataSource = dataset1.tables(combobox1.selecteditem)
C# but easily convertible to VB.Net (I suppose):
String connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""C:\test.mdb""";
String tableName = combobox1.SelectedItem.ToString();
String sqlSELECT = String.Format("select * from [{0}]", tableName);
System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter();
da.SelectCommand = new System.Data.OleDb.OleDbCommand(sqlSELECT, new System.Data.OleDb.OleDbConnection(connectionString));
DataGridView1.DataSource = dataSet1;
DataGridView1.DataMember = dataSet1.Tables(tableName);
da.Fill(dataSet1, tableName);
I was just sketching a proof that "it can be done in a generic way" to your problem, you should elaborate and maybe come with something more elegant (and safe).
Private Sub BindData()
With customersDataGridView
.AutoGenerateColumns = True
.DataSource = customersDataSet
.DataMember = "Customers"
End With
End Sub
Just to clarify this answer. For Future Reference.
Public Class Form1
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\test.accdb;")
Private Sub Button1_Click
Dim da As New OleDbDataAdapter
Dim table As String = ComboBox1.SelectedItem.ToString
Dim sql As String = String.Format("select * from [{0}]", table)
da.SelectCommand = New OleDbCommand(sql, con)
DataGridView1.DataSource = DataSet.Tables(table)
da.Fill(DataSet, table)
End Sub
End Class
Not trying to Ressurect, but i thought the working version of this VB Script should be posted.
I would like to point out that the dataset is held by Visual Studio, hence the strange source string.