vb.net Bind a combobox to a datasource - vb.net

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.

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

Display data in combobox from one winform to another winform

I have this form1 that displays a list of my entries. When I want to update an entry, I will click it in the DataGridView and an update button will be visible. Once I clicked the 'Update' button, form2 will appear and the details of the currently selected row in my dgv will be listed.
My problem is that one of the details involves a data from a combobox. It does not change the value.
This form2 acts as a form to create entries and at the same time to update them. I load the details to this form as is like you are creating one but I am updating them.
Now this combobox has data that has been loaded from the database. Something like this:
Dim cmd2 As New MySqlCommand
Dim dt2 As New DataTable
con.Open()
With cmd2
.Connection = con
.CommandText = "Select staff_name from staff where staff_position='Pre-seller'"
End With
da.SelectCommand = cmd2
da.Fill(dt2)
With cmbseller
.DataSource = dt2
.DisplayMember = "staff_name"
.ValueMember = "staff_name"
End With
con.Close()
All is well, until I need to update an entry. The data in the combo box is not changing from the details of my currently selected row.
For example, the data in the entry for this combobox is 'Leizel', but when I click the update to show form2, it shows a different item. Like the one that has been loaded from the database. It is not adjusting to what I want. I change the other details but not this one.
Can anyone suggest anything?
EDIT:
This is the code I am using in loading data from form1 to form2. obviously this is only a part of it.
Dim frm3 As New SalesOrder
frm3.cmbseller.Text = DataGridView1.Item(2, DataGridView1.CurrentRow.Index).Value
where 2 is the column in my dgv that needs to be displayed in the combobox in form2.

Open Form faster & remove "System.Data.DataRowView" flicker from Combobox data binding

I have plenty Comboboxes on my form (around 20), and all of them are displaying items from different tables of my DB. If I put all code on Form_Load event then Form opens very slow. So I tried to paste code in different varieties, and currently I'm stuck at Combobox_Enter event - now Form loads fast, but when I click on drop-down of combobox I see sometimes "System.Data.DataRowView" flickering before items are loaded in Combobox. Is there any way to achieve both - fast Form opening & Combobox loading Items without flickering ?....So far I tested with Form_Activate,Form_GotFocus(not working) and Combobox_GotFocus,Combobox_MouseHover,Combobox_Click(not exactly perfect). This is an example of how I bind my Comboboxes:
Private Sub Combobox1_Enter(sender As Object, e As EventArgs) Handles Combobox1.Enter
Dim SQL As String = "SELECT Name from MyTable"
Dim dtb As New DataTable()
Using con As OracleConnection = New OracleConnection("Data Source=MyDB;User Id=Lucky;Password=MyPassword;")
Try
con.Open()
Using dad As New OracleDataAdapter(SQL, con)
dad.Fill(dtb)
End Using
Combobox1.DataSource = dtb
Combobox1.DisplayMember = "Name"
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
Combobox1.SelectedIndex = -1
End Using
End Sub
I also tried with declaring " Public con As OracleConnection", but output is same as I have It now.
Any help appreaciated !
When binding a ComboBox or the like, you should pretty much ALWAYS set the DataSource last. You are not and that's why you see "System.Data.DataRowView" displayed.
When you bind a list to a ComboBox, the control will display data from the column or property specified in the DisplayMember if there is one, otherwise it will call ToString on each item. In your code, you first set the DataSource and, at that point, the DisplayMember is not set so the control calls ToString on each item. The result of that is "System.Data.DataRowView". When you then set the DisplayMember, those values that the control just went to the trouble of generating and displaying are discarded and the DisplayMember is used to get new values.
Even if you weren't seeing that effect, you'd still be wasting your control's time generating values that you don't want. ALWAYS set the DisplayMember, ValueMember or the like before setting the DataSource in code unless you have a specific reason not to. The only reason that I'm aware of is when you're binding a CheckedListBox, which has an issue when DataSource is set last.
By the way, shouldn't you have a test there to only retrieve data if there is no data already loaded? You don't want to reload data if the user returns to the same control, do you?

combobox text still showing previous value on change

I am using 1 combobox to populate a 2nd combobox. What is happening however, is that the 2nd combobox dropdown is changing and displaying the correct values but when the change occurs, the text property still retains the old value. I am using items.clear() and thought that would also clear the text value of the combobox.
I am using winforms and would be grateful if someone could point out my newbie error. Thanks
Private Sub cmbCustomer_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbCustomer.SelectedIndexChanged
' This is the routine to populate the departments box with values from customer
sql = "SELECT * from Departments WHERE Customer = ?"
Dim cmd As New OleDb.OleDbCommand
cmd.Parameters.AddWithValue("#p1", cmbCustomer.Text)
cmd.CommandText = sql
cmd.Connection = oledbCnn
dr = cmd.ExecuteReader
cmbDept.Items.Clear()
cmbRequestBy.Items.Clear()
While dr.Read()
cmbDept.Items.Add(dr("Name"))
End While
cmd.Dispose()
dr.Close()
'oledbCnn.Close()
End Sub
You are clearing the Items collection not the Text property of the combo.
This behavior depends on the DropDownStyle property of the combobox.
The default is DropDown that allow the combo to maintain separate inner controls for Items (A List of some kind) and Text (a TextBox)
If you change the property to DropDownList clearing the Items collection will clear also the 'text' part of it.
Of course you loose the possibility to type inside the TextBox portion of the combobox for example to add an item not included in the list
See Microsoft Connect for Microsoft Response to similar question

Refreshing Datagridview From Dataset Issue

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()