Refreshing Datagridview From Dataset Issue - vb.net

I seem to be pulling my hair out over something that seems pretty straight forward in my eyes. I cannot get a datagridview control to update correctly after altering a dataset.
I initially populate a datagridview from a dataset and auto generate the columns no problem. However, if I regenerate my dataset with new data, the datagridview will display the new data correctly, but won't remove the old column headers.
For example, I have a query that gives me Store Name and Manager and auto populates my datagridview. Then if I change my query to just give me Store Name and Supervisor, it gives me Store Name, Manager (with blank column) and Supervisor.
I have tried datagridview.refresh() and datagridview.update() but nothing seems to work.
Here is my code:
MySQLConn.Open()
Dim ExQry As New MySqlCommand(QryStr, MySQLConn)
ExQry.CommandType = CommandType.Text
Dim da As New MySqlDataAdapter(ExQry)
dasCustomQryData.Clear() 'my dataset is called dasCustomQryData
da.Fill(dasCustomQryData, "QryData")
da.Update(dasCustomQryData, "QryData")
With dgvCustomQuery
.DataSource = Nothing
.Dock = DockStyle.Fill
.AutoGenerateColumns = True
.DataSource = dasCustomQryData
.DataMember = "QryData"
.Refresh()
.Visible = True
End With
MySQLConn.Close()
da.Dispose()
dasCustomQryData.Dispose()
So, when I want to update my datagridview, I plugin a new QryStr to the above code and it rebuilds my dataset. The dataset is getting updated, because the datagridview contains the correct data, however, my problem is that the datagridview isn't clearing the old columns that aren't populated anymore.
All help appreciated. Thanks

I would recommend you create a connection and a dataset straight from VB and the in the dataset it shows the tables. At the bottom of the tables is a standard query but u can create your own...with variables as parameters and then you can call the query through the table adapter and assign this straight to the datagridview.
That always seems to work for my programs. What sort of database are u using? Might be obvious but just to make sure, the datagridview is not bound right? Sample from one of my projects dgData.DataSource = TblEventsTableAdapter.ViewEvent(cmbEvents.SelectedItem.ToString) where dgdata is obviously datagridview. ViewEvent is a custom query created in the dataset and takes in 1argument. Hope this is of use to you

Ok, after a bit of troubleshooting and playing around with code, I found that the simple solution to this was that the datatable itself was not releasing the column headers. So even though the datagridview and the dataset was getting cleared, the datatable was still populated.
The following command solved my issue:
dt.Columns.Clear()

Related

DataGridView does not show decimals

I hope somebody can help me since i am unable to find a solution for it on the net.
I am working on a form where a datagridview is filled automatically using a tableadapter with data from a access database. In the database i have a column with doubles containing small decimal numbers. The datagridview is filled correctly except for this one, which does not show the decimals. e.g. "0,00400364688627264" only shows "0" or "0.000000" depending on how i format the column. Even scientific formatting only shows"0.000000E+000" in the dgv. I suspect it has something to do with the separator "," in access and have tried setting the regional location before calling the fill:
System.Globalization.CultureInfo.DefaultThreadCurrentCulture = New Globalization.CultureInfo("da-DK")
But that does not work either. Thought this would be a fairly simple problem, but cannot figure out why it is not working.
Ok, i could not find a solution. I guess it has something to do with the tableadapter fill method and the local setting. Anyway, I made a work around and instead filled the datagridview from a adodb recordset. I will probably hear some complains about this solution but it works :-) Thanks Jimi and Fabio for taking your time.
Dim StamRS As New ADODB.Recordset
Dim dt As New DataTable
Dim StamAD As New OleDb.OleDbDataAdapter
Try
Connection.connect()
StamRS.Open(sqlstr, conn, 1, 3)
If StamRS.RecordCount > 0 Then
StamAD.Fill(dt, StamRS)
Stamopl_DGV.DataSource = dt
End If
Catch ex As Exception
MsgBox("Fejl i åbning af Stamopløsnings databasen.")
Finally
StamRS.Close()
StamRS = Nothing
Connection.closeconn()
End Try

Update Listbox after inserting a row in database

I have a listbox which has a bindingsource which connects to access database. have following code which creates and adds new line to my access database and to datagrid view but changes are not updating in the listbox.
Dim drv As DataRowView = DirectCast(EQtblBindingSource.AddNew(), DataRowView)
drv.BeginEdit()
drv.Row.BeginEdit()
drv.Row("eiD") = "SS"
drv.Row("EQ_NAME") = "DUMMY"
drv.Row.EndEdit()
drv.DataView.Table.Rows.Add(drv.Row)
EQ_tblTableAdapter.Update(EQDATADataSet.EQ_tbl)
EQtblBindingSource.ResetBindings(True)
Is there a way to reflect changes immediately after i add a new row? resetbindings seems not working or another option to reload or refresh my listbox. Any idea please help.
Thanks
Make sure that the DataSource for your listbox is set to the bindingsource.
Your code can be simplified to this:
With EQtblBindingSource
.AddNew()
DirectCast(.Current, DataRowView)("eiD") = "SS"
DirectCast(.Current, DataRowView)("EQ_NAME") = "DUMMY"
.EndEdit()
End With
EQ_tblTableAdapter.Update(EQDATADataSet.EQ_tbl)

Error when trying to add a row to an already existing data table and grid view

I currently have a gridview that I am able to populate with a query. On a button click I would like to run the query again with a new value and add the new information to what is already displayed in the gridview. I am attempting to do this by copying the information that is currently in the gridview into a datatable then adding a row to the table then resetting the binding on the gridview and refreshing the gridview. The problem is I get an error when trying to add the new row (System.Data.NoNullAllowedException: 'ColumnName' does not allow nulls.
Here is the code I am trying to use for this process. Any help would be much appreciated.
Dim EpicorCM As New SqlCommand(JobSelect, EpicorCon)
EpicorCon.Open()
Dim EpicorReader As SqlDataReader = EpicorCM.ExecuteReader
Dim JobInfoTable As New DataTable
JobInfoTable = CType(dgvJobInfo.DataSource, DataTable).Copy
JobInfoTable.Rows.Add(EpicorReader)
dgvJobInfo.AutoGenerateColumns = True
dgvJobInfo.DataSource = JobInfoTable
dgvJobInfo.Refresh()
EpicorCon.Close()
You are trying to add a SqlDataReader to the Rows collection but that will not work. It only compiles because the Add() method has an overload that is params of Object.
Fortunately DataTable has a method to load a reader. Instead of this:JobInfoTable.Rows.Add(EpicorReader), do this:
JobInfoTable.Load(EpicorReader)
As an aside, commands and readers are Disposable resources so you can leak memory by not disposing of them either in Using blocks or in Finally blocks.

Anyway to Check if any datatable.Columns is added vb.net

I have a dataset with a datatable with Columns.
I fill dataset with this code in Winforms
myAdapter = New SqlDataAdapter("Select * from users", strSqlConn)
myAdapter.Fill(dsDataset, "Users")
dcPk(0) = dsDataset.Tables("Users").Columns("FirstName")
dcPk(1) = dsDataset.Tables("Users").Columns("LastName")
dsDataset.Tables("Users").PrimaryKey = dcPk
Is it anyway to check if any datatable.Columns is added vb.net? Later in code For example "amount" is added
dsDataset.Tables("Users").Columns.Add("amount", System.Type.GetType("System.Int32"))
What I really want - I have alot of datasets and I want to see if it any real changes in them (not added columns whois not part of the database) if not, dont save to database.
When I use GetChanges it says I have changes if I have added columns, but the added columns should be excluded.
Now I have hardcoded the added columns to exclude them in the check, it works but thats not a good way to maintain. Another way is to make a copy of all datasets and compare them, in the copy there is no added columns. But Im not sure about performance when its alot of datasets...
Like in rows
If row.RowState = DataRowState.Added Then
'Do something
end if
You should be able to use the GetChanges() method of the DataTable object, like so...
dim t as DataTable = MyDataTable.GetChanges()
If t IsNot Nothing then
' There were changes to the table
Else
' There were no changes to the table
End If
Please be sure to read the documentation page that I linked to be sure that it meets your requirements.

vb.net Bind a combobox to a datasource

Over the past few days, I've read about a thousand forum posts, and looked at many code samples, but I still can't figure this out.
My goal is to populate a combobox with values from an Access 2007 query. I can do this by using the DataSource, DisplayMember and ValueMember properties, but regardless of the data in the query, the comboboxes all just default to the to first item in the items collection and don't change when the main BindingSource is moved. I am binding the controls with this line of code:
ComboBox1.DataSource = DataSet1.qryItemSourceTest
ComboBox1.DisplayMember = "SourceTestDisplayField"
ComboBox1.ValueMember = "SourceTestIDField"
Combobox1.DataBindings.Add(New Binding("SelectedValue", qryTestBindingSource, "TestField", True))
I have also tried using a BindingSource as a DataSource.
I have also tried using an array as a DataSource.
If I drag the control on from the Data Source tab in the IDE, it will scroll through records properly, but it will only display the value and not the query 'look-up' value that I want the combobox to display. I have tried changing the DisplayMember and ValueMember properties of the combobox after dragging it on from the Data Sources tab and that seems to break the functionality as well.
I'm looking for some best practices here. I know I'm missing something easy here and I apologize for post an issue that has already been covered so many times, but I could use some individual help here.
Edit: I eventually was able to accomplish my goal using the Visual Studio IDE Properties window. The second property on a control is a Data Bindings property which expands into exactly what I needed. I just never saw this before because it was not in alphabetically order like everything else.
Hi you can do this code to populate data into combo
Try
Dim cn As New OleDbConnection
cn.ConnectionString = conString
cn.Open()
cmd.Connection = cn
cmd.CommandText = "your query"
'Execte reader function is used to hold more than one value from the table
dr = cmd.ExecuteReader()
' Fill a combo box with the datareader
Do While dr.Read = True
ComboBox1 = dr.Item(0)
Loop
cn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
If you have any more problems don't hesitate to ask.