refreshing datagridview after populate existing datatable in vb.net - vb.net

I am working on a windows form application using VB.net. I have populated a Datagridview1( dataset1.existingtable is the datatable). Now i wish to get distinct values from one column of its datatable and then populate another Datagridview2(dataset2.uniquerecords is the datatable).
PROBLEM: Not able to refresh data in Datagridview2 using design mode. However i am able to refresh data when dynamically creating a datatable at runtime.
The below sub is called after an event after my form has loaded completely.
The below code does NOT work
Private Sub loaddistinctrecords()
uniquerecords = existingtable.DefaultView.ToTable(True, "column_name")
Datagridview2.Refresh()
End Sub
The below code works
Private Sub loaddistinctrecords()
Dim newuniquerecords As New DataTable()
newuniquerecords = existingtable.DefaultView.ToTable(True, "column_name")
Datagridview2.DataSource = newuniquerecords.DefaultView
End Sub

well it looks like one cannot directly assign a datatable to another datatable and expect the datagridview to update automatically if the datatable was created from design mode.
What one can do is simply clear the existing records and then merge records from the source datatable.
Private Sub loaddistinctrecords()
uniquerecords.Clear()
uniquerecords.Merge(existingtable.DefaultView.ToTable(True, "table_name"))
End Sub

Related

How to filter datagridview by string in textbox in visual basic without using SQL query WHERE?

I'm trying to filter rows of datagridview based on textBox value. I want to remove all rows which don't have values like in column NAZIV. I'm new in visual basic.
Name of datagridView is dvgIQ
I've tried this but it's not working.
Sub filter
If textBox1.Text.Length>=3 Then
For i As Integer = dvgIQ.Count-1 To 0 Step -1
If Not dvgIQ.Rows(i).Cells(4).Value.ToString(textBox1.Text.ToLower) Then
dvgIQ.Rows.RemoveAt(i)
End If
Next i
Else If textBox1.Text.Length>0 And textBox1.Text.Length<3 Then
MsgBox("warning")
End If
End Sub
Thanks in advance
You should start by populating a DataTable with your data. If the data comes from a database then use a data adapter and call its Fill method or else use a data reader and call Load on the DataTable. If the data is not from a database then you can build and populate the DataTable manually.
Next, bind the Datatable to a BindingSource that you added to the form in the designer. Finally, bind the BindingSource to your grid:
BindingSource1.DataSource = myDataTable
DataGridView1.DataSource = BindingSource1
To filter the grid, you simply set the Filter property of the BindingSource, e.g.
BindingSource1.Filter = $"SomeColumn LIKE '{TextBox1.Text}%'"
That will exclude all rows where SomeColumn does not start with the text in TextBox1. You should read the documentation for the Filter property and follow the specified link to learn what syntax is supported by ADO.NET. It is a small subset of SQL.

How to delete and clear the datagridview rows in vb 2010

I am developing a Point of Sale System in VB and using access as RDBMS. Everything went well however when it came to deletion i got stuck. I want to clear all the rows from the datagridview and want to delete it from database also. The new datagridview will store new items and i am sending that new data to print.I tried the below codes but all in vain.
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
For i As Integer = 0 To SProductDataGridView.RowCount
SProductDataGridView.Rows.Remove(SProductDataGridView.Rows(0))
Next
End Sub
2nd Try
For i As Integer = 0 To SProductDataGridView.RowCount -1
ProductTableAdapter.DeleteProduct(IDTextBox.Text)
ProductTableAdapter.Fill(MyDS.product)
ProductTableAdapter.Dispose()
Next
Note : gridview.rows.clear() + gridview.ds = nothing , i tried that butgridview.rows.clear() doesn't work and gridview.ds = nothing just clear the gridview and is not deleting data from access database.
You can use either of below options:
Using DataTable
Using DataGridView
Using BindingSource
The logic of all solutions is removing the rows and then updating the table adapter.
Using DataTable
You can find each rows in the data table and delete it, then update the table adapter:
For Each row As DataRow In Me.TestDBDataSet.TestTable.Rows
row.Delete()
Next
Me.TestTableTableAdapter.Update(TestDBDataSet.TestTable)
Using DataGridView
For Each row As DataGridViewRow In Me.TestTableDataGridView.Rows
DirectCast(row.DataBoundItem, DataRowView).Delete()
Next
Me.TestTableTableAdapter.Update(TestDBDataSet.TestTable)
Using BindingSource
For Each item As Object In TestTableBindingSource
TestTableBindingSource.Remove(item)
Next
Me.TestTableTableAdapter.Update(TestDBDataSet.TestTable)

Showing a single record in datagridview from access database vb.net

What I have is a small application that has a datagridview and an Access DB. There are 10 records in the database and they all show up in the datagridview when the app is launched. I need to be able to do two things:
I need to be able to enter an id number in a textbox and have JUST that record show in the DGV.
I need to be able to have it show all the records again (using a different click event of course).
I am able to choose the record with this:
Dim row As DataRow
row = ProductsDataSet.tblProducts.FindByItemNum(txtNumber.Text)
but I am unable to figure out how to show just that record in the DGV.
(Let me clarify...I THINK I am choosing the record simply because no exceptions are being thrown).
Any guidance here would be greatly appreciated. Thank you.
John
An option is to set the dataSource of your dataGridView to the data you'd like to display. Below is an implementation using dataTables.
Class MyForm
Dim dataTableAll, dataTableOneID, As DataTable
Sub show1ID_Click
Dim id As Integer = InputBox("Enter ID")
dataTable2 = dataTable1.Select("[ID] = id").CopyToTable
dataGridView.DataSource = dataTableOneID
End Sub
Sub showAll_Click
dataGridView.DataSource = dataTableAll
End Sub
End Class

Faux Databinding a Recordset to a Datagridview

I am updating a very old vb6 program that includes recordsets bound to an old third party grid control. The recordset functionality is so ingrained into the program that it is not an option to replace them. So, I replaced the unfunctional grid with a datagridview and I fill it using a dataadapter and a dataset. The problem is that the recordset was originally bound to the grid and using a dgv breaks the binding.
So this is what I am trying to do. I have a function that passes in the old recordset and the new dgv, and fills it. I would like to create a dynamic handler to the dgv's selectionchanged event to update the rs with the current position on the dgv (rs.aboluteposition = dgv.row), thus updating the rs cursor to the current position in the dgv, making a sort of faux data binding.
Something like this....
AddHandler dgv.SelectionChanged, AddressOf RefreshRecordset
Public Sub RefreshRecordset()
myRS.AbsolutePosition = dgv.Row
End Sub
A couple things though. I have to track if the event handler was already created, and the associated recordset that goes with this specific datagridview. Also, since this is a global function to update many dgvs with many rs, it needs to have a way to track the recordset. I was thinking of somehow using the tag of dgv? Maybe create a dictionary of all the recordsets then look it up by the name of the dgv?
Below is my original method that worked pretty well. I eventually refined it and put it in a class for each recordset. I also updated it to accept true dbgrids. By wrapping it in a class, I was able to remove the dictionaries. In the New function, I pass in either grid and a recordset. From there, I set up event handlers to handle both the grid row change and also the recordset MoveComplete event. I had to use the MoveComplete because the RecordsetChangeComplete has a bug and doesn't always fire correctly. I just check in the MoveComplete if the record count had changed. If so, refresh the grid. Lastly, I added a removehandler for each of the events in the finalize function.
////// The Original Answer //////
For instance, like this... (I CAN'T believe this worked...)
Public dict as new Dictionary(Of String, ADODB.Recordset)
Public Sub FillGrid(ByRef dgv as DataGridView, ByRef rs as ADODB.RecordSet)
'.... Fill the grid with the tableadapter, blah blah.
If Not dict.ContainsValue(rs) Then
dict.add(dgv.Name, rs)
AddHandler dgv.SelectionChanged, AddressOf RefreshRecordset)
' To make the event fire correctly, I think
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End if
End Sub
Public Sub RefreshRecordset(sender As Object, e As System.EventArgs)
Dim dgv as DataGridView = Ctype(sender, DataGridView)
If dict.ContainsKey(dgv.Name) then
Dim rs as ADODB.Recordset = dict(dgv.Name)
rs.AbsolutePosition = dgv.CurrentCell.RowIndex
End if
End Sub
Now I need to create a handler to the recordset to refresh the dgv everytime the recordset is updated.
And btw, I know there are probably other ways to do this and I would absolutely would love to hear them! Please feel free!
Thanks!

New added items on the datagridview cannot be seen at runtime

I have a program that inserts data in access database and the user can view the newly added items in a data grid view. After i add new items to the database it cannot be seen in the datagridview while the program is running. I have to stop the program and run it again just to see the changes i made.
Here is how i load the datagridview:
Public Class frmSupplies
Private Sub frmSupplies_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'SuppliesDataSet.product_info' table. You can move, or remove it, as needed.
Me.Product_infoTableAdapter.Fill(Me.SuppliesDataSet.product_info)
End Sub
How can i view the newly added items while the program is still running?
I created a module that will call the "refresh" function for the datagridview. I added a new module to my project and added this codes:
Imports System.Data.OleDb
Module Module1
Dim con As New OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;Data Source= database path")
Sub REFRESHDGV()
Dim sql As String
sql = "SELECT * FROM [product info]"
Dim adapter As New OleDbDataAdapter(sql, con)
Dim dt As New DataTable("product info")
adapter.Fill(dt)
Form1.dgv1.DataSource = dt
End Sub
End Module
Hope this helps others!
Try wrapping around beginedit ... end edit
gridview.BeginEdit();
----
gridview.EndEdit();
I am not familiar with access (I use oracle). Oracle database can notify you if something has changes in your database, so you can refresh the datagridview. In your case you can have a button (for refresh the datagridView) or a timer and refresh it every x time (you know the time):
'I imagine that you have a bindingSource
bindingSource1.DataSource = Product_infoTableAdapter.GetData()
bindingSource1.ResetBindings(false)
Maybe you want to take a look in DataGridView DataBinding
When you bind an Access table to a grid on a Windows form and then change the data outside that application, the form or the grid simply do not have a way of knowing that data was changed, unless 1) they receive some kind of notification from Access, or 2) the application keep querying the data source to see if changes were made.
Option 1 there is not applicable with MS Access.
Your only option is to put a timer on the form to regularly check for changes (on a fixed interval) and reload the table and refresh the grid if changes were found.