Datagridview how to fill data from another datagridview - vb.net

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.

Related

Visual Studio Vb.net loaded dataset from oracle query missing or replacing first row of data

I have a vb.net application program that is suppose to query a oracle/labdaq database and load the dataset into a datatable. For some reason the query works fine and there is no exception thrown, however, when I load the data it seems to be missing the first row. I first noticed the issue when I did a query for a single row and it returned zero rows when I checked the datatable's row amount during debugging. I then compared all my data sets to a data miner application straight from the oracle source and i seems to always be missing one, the first, row of data when I use the application.
here is the code... I changed the query string to something else to maintain company privacy
Private Sub CaqOnSQL(strFileDirect As String)
Try
Dim connString As String = ConfigurationManager.ConnectionStrings("CA_Requisition_Attachments.Internal.ConnectionString").ConnectionString
Dim conn As New OracleConnection With {
.ConnectionString = connString
}
Dim strQuerySQL As String = "SELECT * FROM REQUISITIONS " &
"WHERE DATE BETWEEN TO_DATE('12/10/2020','MM/dd/yyyy') AND " &
"TO_DATE('12/14/2020','MM/dd/yyyy') " &
"ORDER BY ID"
conn.Open()
Dim Cmd As New OracleCommand(strQuerySQL, conn) With {
.CommandType = CommandType.Text
}
Dim dr As OracleDataReader = Cmd.ExecuteReader()
dr.read()
Dim dt As New DataTable
dt.TableName = "RESULTS"
dt.Load(dr)
ExcelFileCreation(dt, strFileDirect)
You should remove the line:
dr.read()
The call to Read is what is causing you to skip the first row, when combined with the DataTable Load method.
In addition, I have taken the liberty to make some additional changes to your code for the purposes of Good Practice. When using Database objects like Connection and Command, you should wrap them in Using blocks to ensure the resources are released as soon as possible.
Dim dt As New DataTable()
dt.TableName = "RESULTS"
Using conn As New OracleConnection(connString)
conn.Open()
Dim strQuerySQL As String = "SELECT * FROM REQUISITIONS " &
"WHERE DATE BETWEEN TO_DATE('12/10/2020','MM/dd/yyyy') AND " &
"TO_DATE('12/14/2020','MM/dd/yyyy') " &
"ORDER BY ID"
Using command = New OracleCommand(strQuerySQL , conn)
Using dataReader = command.ExecuteReader()
dt.Load(dataReader)
End Using
End Using
End Using
Note: Be wary of Using blocks when using a DataReaderas you may find the connection is closed when you don't want it to be. In this case, the DataReader is used entirely within this function and is safe to use.

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

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.

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.

Update grid from a query

I have a Visual Basic 2010 application that uses a DataGridView to display a list of frequencies from a Microsoft Access 2010 database. The application uses the BindingNavigationPostionItem to allow navigation though the table.
The Move Next and Move Previous buttons move you up and down the list. The cool thing is, as you do this, I have code that sends the Frequency and Mode to my Yeasu radio and the radio then is set to that freq/mode.
This works great but, if I try to filter the DataGridView by the Service field, the ID field becomes blank and navigation does not work.
Here is the code that runs after you select what you want to filter by and you click the filter button:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmbox1 As String
cmbox1 = ComboBox1.Text
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from HFUtil where service = '" & cmbox1 & "'", MyConn) '
da.Fill(ds, "HFUtil")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
BindingNavigator1.BindingSource = source1
DataGridView1.Refresh()
BindingNavigator1.Refresh()
'=========================================================
ListBox1.Items.Clear()
ListBox1.Text = ""
For Each dr As DataRow In ds.Tables(0).Rows
Dim sItemTemp As String
sItemTemp = String.Format("{0} {1} {2}", dr("freq"), dr("mode"), dr("desc"))
ListBox1.Items.Add(sItemTemp)
Next
ComboBox2.Items.Clear()
ComboBox2.Text = ""
For Each dr As DataRow In ds.Tables(0).Rows
Dim sItemTemp As String
sItemTemp = String.Format("{0} {1} {2}", dr("freq"), dr("mode"), dr("desc"))
ComboBox2.Items.Add(sItemTemp)
Next
End Sub
The only difference between this code and the code that runs on form load is - where clause in the data adapter.
What am I doing wrong?
I don't see in your code where you apply your filter. So, lets pretend for a second that you load your whole table into DataSet. Then next thing, you either use DataSet.DefaultView or create your custom DataView and assign this to DataSource property - you did this.
Now, all you have to do is apply row filter to the data view you use
view.RowFilter = "service = '" & cmbox1 & "'"
At this point you should only see subset of records and nothing should happen to your Id field. Because your data doesn't change.
I have suspicion, you changing your view somewhere and this is why you have problems.

How to create a ComboBox autofill using SQLite Data Reader

I have two Combo-Boxes like this
I need to create an auto-fill feature for the 1st Combo-Box. It should list the EmployeeID if Search-By Field is specified as Employee-Number. Similarly it should list Employee First Name along with Last Name if the Search-By Field is Employee-Name.
How can I do this? I have no clue, I am doing this for the first time. I am using SQLite, Visual Studio 2010.
Dim mySelectQuery As String = "SELECT " & Search & " FROM EmployeeTable WHERE Status LIKE '" & Status & "'"
Dim myConnString As String = "Data Source=" & Application.StartupPath & "\Database\SimpleDB.db3"
Dim sqConnection As New SQLiteConnection(myConnString)
Dim sqCommand As New SQLiteCommand(mySelectQuery, sqConnection)
sqConnection.Open()
Try
' Always call Read before accessing data.
Dim sqReader As SQLiteDataReader = sqCommand.ExecuteReader()
Dim j As Integer = sqReader.FieldCount
While sqReader.Read()
'''''''''''''''''''''''Here, Don't know how to list the items from the query reult into the combo-box
End While
'Close Reader after use
sqReader.Close()
Catch ex As Exception
'Show Message on Error
MsgBox(ex.ToString)
Finally
'At Last Close the Connection
sqConnection.Close()
End Try
I'm not sure entirely what you are asking but I think this is it.
In the SelectedIndex changed event you would have something similar to the code below. You can add an If statement to check what you are querying for and adjust your query accordingly.
Dim dt as New DataTable
Try
Using sqlConn
sqlConn.Open()
Using cmd As New SqlCommand("your query")
cmd.Connection = sqlConn
cmd.CommandType = CommandType.Text
Dim reader as SqlDataReader = cmd.ExecuteReader()
dt.Load(reader)
End Using
End Using
Catch ex As SqlException
Throw New Exception(ex.Message)
End Try
With yourComboBox
.DataSource = dt
.DataValueField = "columName you want to be the value of the item"
.DataTextField = "columnName of the text you want displayed"
End With
Notice the following properties for the combo-box: AutoCompleteMode, AutoCompleteSource, AutoCompleteCustomSource.
Select the appropriate AutoCompleteMode. See details on the different modes at this link.
For AutoCompleteSource, choose either ListItems (in which case the source will be the items of the ComboBox) or CustomSource. Should you choose CustomSource, set the appropriate source as the value of the ComboBox's AutoCompleteCustomSource property.
This should provide you with enough details to do what you're looking for.
The other requirements you've listed - such as taking the data from an SQLite database or changing between employee name and employee number - won't affect the way you work with the AutoComplete feature.