Populate data from dataset and show in datagridview - vb.net

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.

Related

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.

How to store database resultset?

I want to know which is the best way to store database value in vb.net, For example, I've this code:
Dim conn As MySqlConnection = Connection() 'Return a connection obj
conn.Open()
Dim transaction = conn.BeginTransaction
Dim cmd = New MySqlCommand("SELECT * FROM tb ORDER BY ID")
Dim ResultSet = Cmd.ExecuteReader
If ResultSet.HasRows Then
Do While ResultSet.Read
'Here the value should be store
Loop
End if
How you can see I take all table from my database, now I want store each records in a structure that allow me to access it like the table. An array is good for do this? A list? Which is the best way?
There is no best way. You have different options. For example:
As an option you can use a DataTable
Also you can store values in a generic List(Of T).
If you prefer working with DataTable it will be more simple to use DataAdapter to fill the DataTable. This way you can also create your List(Of T) from your DataTable.
Example of Using DataDapter to fill DataTable
Dim Connection = "Connection String"
Dim Command = "SELECT * FROM Category"
Dim Adapter = New SqlDataAdapter(Command, Connection)
Dim Table = New DataTable()
Adapter.Fill(Table)
This way the DataTable will have columns with name of columns in your result set.
Also you can fill your data in a List(Of T) using the DataTable this way:
Dim ListOfCategory = Table.Rows.Cast(Of DataRow) _
.Select(Function(Row)
Return New Category With
{
.Id = Row.Field(Of Integer)("Id"),
.Name = Row.Field(Of String)("Name")
}
End Function).ToList()
Note
If can change the way you are writing your application, you can use Entity Framework as a good option to work with data.

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

VB.NET: Clear DataGridView

I've tried -
DataGridView1.DataSource=Nothing
and
DataGridView1.DataSource=Nothing
DataGridView1.Refresh()
and
DataGridView1.RefreshEdit()
None of them works..
I've written a method that sets the DataSource of the DataGridView when executed. but each time i execute it, it replicates the data with new value and appends it to the previous contents of the DGV.. I wanna clear the content and then add the values.. Is that possible?
If the DataGridView is bound to any datasource, you'll have to set the DataGridView's DataSource property to Nothing.
If the DataGridView is not bound to any data source, this code will do the trick:
DataGridView.Rows.Clear()
For unbound cases note that:
DataGridView.Rows.Clear()
leaves the Columns collection in place.
DataGridView.Columns.Clear()
..will remove all the columns and rows. If you are using the DGV unbound, and on next use the columns change, clearing the Rows may not be adequate. For library code clear all the columns before adding columns.
I'd probably use this...
DataGridView1.Rows.Clear()
to clear out the rows and then rebind.
Follow the easy way like this
assume that ta is a DataTable
ta.clear()
DataGridView1.DataSource = ta
DataGridView1.DataSource = Nothing
Can you not bind the datagridview to an empty collection (instead of null). That do the trick?
To remove the old record in datagridview when you are searching for new result,with button_click event write the following code,
me.DataGridview1.DataSource.clear()
this code will help to remove the old record in datagridview.
I found that setting the datasource to null removes the columns. This is what works for me:
c#:
((DataTable)myDataGrid.DataSource).Rows.Clear();
VB:
Call CType(myDataGrid.DataSource, DataTable).Rows.Clear()
My DataGridView is also bound to a DataSource and myDataGridView.Columns.Clear() worked fine but myDataGridView.Rows.Clear() did NOT. Just an FYI for those who have tried .Rows.
Don't do anything on DataGridView, just clear the data source. I tried clearing myDataset.clear() method, then it worked.
I've got this code working in a windows form,
Public Class Form1
Private dataStuff As List(Of String)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
DataGridView1.DataSource = Nothing
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dataStuff = New List(Of String)
dataStuff.Add("qwerty")
dataStuff.Add("another")
dataStuff.Add("...and another")
DataGridView1.DataSource = dataStuff
End Sub
End Class
You should remove the table from dataset if the datagrid is bind to some datatable. Your Gridview will be cleared automatically. No other way.
[YourDatasetName].Tables.Clear()
I had the same problem on gridview content clearing. The datasource i used was a datatable having no columns, and i added columns and rows programmatically to datatable. Then bind to datagridview. I tried the code related with gridview like gridView.Rows.Clear(), gridView.DataSource = Nothing
but it didn't work for me. Then try the below code related with datatable before binding it to datagridview each time.
dtStore.Rows.Clear()
dtStore.Columns.Clear()
gridView.DataSource = dtStore
And is working fine, no replication in DataGridView
1) create button named it Clear.Inside insert tfhe following code
datagridviewer.DataSource=nothing
2) In your search button begin your code by the following statement
datagridviewer.DataSource = DataSet.table
Nb:instead of table put the real name of your table
ex: datagridviewer.DataSource = DataSet.client
When feeding info from an SQL query into a datagridview you can clear the datagridview first before reloading it.
Where I have defined dbDataSet as New DataTable I can do a clear.
dbDataSet must be at the start of the form within the Public Class Form
Dim dbDataset AS New DataTable
within the code of you Private Sub, place
dbDataSet.Clear()
You may have a user scenario such that you want to keep the data binding and only temporarily clear the DataGridView. For instance, you have the user click on a facility on a map to show its attributes for editing. He is clicking for the first time, or he has already clicked on one and edited it. When the user clicks the "Select Facility" button, you would like to clear the DataGridView of the data from the previous facility (and not throw an error if it's his first selection). In this scenario, you can achieve the clean DataGridView by adapting the generated code that fills the DataGridView. Suppose the generated code looks like this:
Try
Me.Fh_maintTableAdapter.FillByHydrantNumber(Me.Fh2010DataSet.fh_maint, hydrantNum)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
We are filling the DataGridView based on the hydrant number. Copy this code to the point where you want to clear the DataGridView and substitute a value for "hydrantNum" that you know will retrieve no data. The grid will clear. And when the user actually selects a facility (in this case, a hydrant), the binding is in place to fill the DataGridView appropriately.
If the DataGridView is bound to any datasource,
DataGridView1.DataSource = Nothing
DataGridView1.DataBind()
Dim DS As New DataSet
DS.Clear() - DATASET clear works better than DataGridView.Rows.Clear() for me :
Public Sub doQuery(sql As String)
Try
DS.Clear() '<-- here
' - CONNECT -
DBCon.Open()
' Cmd gets SQL Query
Cmd = New OleDbCommand(sql, DBCon)
DA = New OleDbDataAdapter(Cmd)
DA.Fill(DS)
' - DISCONNECT -
DBCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
If the GridView (Say the name is gvArchive) is bound to any DataSource, the following will clear it:
gvArchive.DataSource = Nothing
gvArchive.DataBind()
just write this
DataGridView1.DataSource = ""
I had the same problem: I was programmatically binding my GridView1 to one SQL table [dictonary] or another [meny] BUT when I selected the second table from my RadioButtonList1, I was getting an error (System.Web.HttpException: Field or property with the title [the first column's title from the previously selected table] was not found in the selected data source.) i.e. saying that the columns from my first-selected table couldn't be found. All I needed to do was insert:
GridView1.Columns.Clear()
before adding the table columns. Here goes the full code:
Dim connectionString As String = "your-string-details"
Dim connection As New SqlConnection(connectionString)
Then comes your first Sub:
Private Sub BindOrders()
connection.Open()
Dim sqlCommand As String = "SELECT * FROM [dictionary]"
Dim dataAdapter As New SqlDataAdapter(sqlCommand, connection)
Dim dt As New DataTable()
dataAdapter.Fill(dt)
GridView1.Columns.Clear() ' clear columns before adding new ones
If GridView1.Columns.Count <= 0 Then
Dim Field As New BoundField()
Field.DataField = "id"
Field.HeaderText = "id"
GridView1.Columns.Add(Field)
Field = New BoundField()
Field.DataField = "strArHundreds"
Field.HeaderText = "strArHundreds"
GridView1.Columns.Add(Field)
Field = New BoundField()
Field.DataField = "strArTens"
Field.HeaderText = "strArTens"
GridView1.Columns.Add(Field)
Field = New BoundField()
Field.DataField = "strArSingles"
Field.HeaderText = "strArSingles"
GridView1.Columns.Add(Field)
End If
GridView1.DataSource = dt
GridView1.DataBind()
connection.Close()
End Sub
Then comes your second Sub:
Private Sub BindDocuments()
connection.Open()
Dim sqlCommand As String = "SELECT * FROM [meny]"
Dim dataAdapter As New SqlDataAdapter(sqlCommand, connection)
Dim dt As New DataTable()
dataAdapter.Fill(dt)
GridView1.Columns.Clear() ' clear columns before adding new ones
If GridView1.Columns.Count <= 0 Then
Dim Field As New BoundField
Field = New BoundField
Field.DataField = "id"
Field.HeaderText = "id"
GridView1.Columns.Add(Field)
Field = New BoundField
Field.DataField = "nazev"
Field.HeaderText = "nazev"
GridView1.Columns.Add(Field)
End If
GridView1.DataSource = dt
GridView1.DataBind()
connection.Close()
End Sub
Finally comes your RadioButton:
Protected Sub RadioButtonList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RadioButtonList1.SelectedIndexChanged
Dim index As Integer
index = RadioButtonList1.SelectedIndex
Select Case index
Case 0
BindOrders()
Exit Select
Case 1
BindDocuments()
Exit Select
End Select
End Sub
For completion, here is the code for the GridView1 and the RadioButtonList1 in the associated aspx.file:
<asp:RadioButtonList ID="RadioButtonList1"
runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
<asp:ListItem>Obraty</asp:ListItem>
<asp:ListItem>Dokumenty</asp:ListItem>
</asp:RadioButtonList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
</asp:GridView>
This all works well now.
The mistake that you are making is that you seem to be using a dataset object for storing your data. Each time you use the following code to put data into your dataset you add data to the data already in your dataset.
myDataAdapter.Fill(myDataSet)
If you assign the table in your dataset to a DataGridView object in your program by the following code you will get duplicate results because you have not cleared data which is already residing in your dataset and in your dataset table.
myDataGridView.DataSource = myDataSet.Tables(0)
To avoid replicating the data you have to call clear method on your dataset object.
myDataSet.clear()
An then assign the table in your dataset to your DataGridView object.
The code is like this.
myDataSet.clear()
myDataAdapter.Fill(myDataSet)
myDataGridView.DataSource = myDataSet.Tables(0)
You can try this code:
' clear previous data
DataGridView2.DataSource = Nothing
DataGridView2.DataMember = Nothing
DataGridView2.Refresh()
Try
connection.Open()
adapter1 = New SqlDataAdapter(sql, connection)
' clear data already in the dataset
ds1.Clear()
adapter1.Fill(ds1)
DataGridView2.DataSource = ds1.Tables(0)
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Use this code where ever you want to implement clear datagridview command
datagridview1.datasource= nothing
datagridview1.datasource= ds
dt.clear() 'Dt as new DATATABLE
ds.clear() 'Ds as new Dataset
this code will clear the datagridview and wil stop data duplication when populating data from database.
You can do in this way:
DataGridView1.Enable = false
DataGridView1.DataSource = Nothing
DataGridView1.Enable = true
For the Clear of Grid View Data You Have to clear the dataset or Datatable
I use this Code I clear the Grid View Data even if re submit again and again it will work
Example
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dar As OleDbDataReader
Dim dt As New DataTable
If (con.State <> 1) Then
con.Open()
End If
dt.Clear() 'To clear Data Every time to fresh data
cmd.Connection = con
cmd.CommandText = "select * from users"
da.SelectCommand = cmd
da.Fill(dt)
DataGridView1.DataSource = dt
DataGridView1.Visible = True
cmd.Dispose()
con.Close()
You can do that only by the following 2 lines:
DataGridView1.DataSource=Nothing
DataGridView1.DataBind()
You can also try this code if you want to clear all data in your DataGridView
DataGridView1.DataSource.Clear()
Try this for a specific cell:
Datagrid.Rows(RowIndex).Cells(ColIndex).Value = DBNull.Value
DgRemolques is the name of my Data grid on WPF
dgRemolques.ItemsSource = Nothing
but i need to clean also de DataTable
dtRemolques.Clear()