vb.net How to overwrite the text in a combobox after the dropdownclosed event - vb.net

I created this piece of code to illustrate the idea, it uses a combobox and a textbox
Private Sub ComboBox2_DropDown(sender As Object, e As EventArgs) Handles ComboBox2.DropDown
ComboBox2.Items.Clear()
ComboBox2.Items.Add("0001 | Apple")
ComboBox2.Items.Add("0002 | Pear")
ComboBox2.Items.Add("0003 | Banana")
ComboBox2.Items.Add("0004 | Pineapple")
ComboBox2.Items.Add("0005 | Cherry")
End Sub
Private Sub ComboBox2_DropDownClosed(sender As Object, e As EventArgs) Handles ComboBox2.DropDownClosed
Dim selecteditem As String = ComboBox2.Items(ComboBox2.SelectedIndex)
ComboBox2.Text = Strings.Left(selecteditem,4)
TextBox2.Text = Strings.Left(selecteditem,4)
End Sub
When I select an item from the combobox what happens is that the combobox keeps showing the whole string while the textbox only shows the first 4 characters.
How can I overwrite the combobox text after I close the combobox?
* edit *
I tried a combo of the solutions but ran into a problem because the data was bound to a datasource so it's not possible to change the item.
This is the new code:
Private Sub ComboBox2_DropDown(sender As Object, e As EventArgs) Handles ComboBox2.DropDown
SQL.ExecQuery($"select ID, Name, RTRIM(ID + ' | ' + Name) as SingleColumn from GCCTEST.dbo.tblFruit")
ComboBox2.DataSource = SQL.DBDT
ComboBox2.DisplayMember = "SingleColumn"
End Sub
Private Sub ComboBox2_DropDownClosed(sender As Object, e As EventArgs) Handles ComboBox2.DropDownClosed
ComboBox2.DisplayMember = "ID"
ComboBox2.SelectedIndex = 0
End Sub
Now I only need to have the 0 be the index I chose...

The following should work.
If not necessary, don't populate the combobox on every drop-down, instead call the FillComboBox-method when loading the Form.
Private Sub FillComboBox()
SQL.ExecQuery($"select ID, Name, RTRIM(ID + ' | ' + Name) as SingleColumn from GCCTEST.dbo.tblFruit")
ComboBox2.DataSource = SQL.DBDT
ComboBox2.DisplayMember = "ID"
ComboBox2.ValueMember = "ID"
End Sub
Private Sub ComboBox2_DropDown(sender As Object, e As EventArgs) Handles ComboBox2.DropDown
Me.ComboBox2.DisplayMember = "SingleColumn"
End Sub
Private Sub ComboBox2_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox2.SelectionChangeCommitted
Dim selV As Object = Me.ComboBox2.SelectedValue
Me.TextBox2.Text = CStr(selV)
Me.ComboBox2.DisplayMember = "ID"
'Set the current value again, otherwise the combobox will always display the first item
Me.ComboBox2.SelectedValue = selV
End Sub

I used a few properties and .net String.SubString method instead of the old vb6 Strings.Left.
Private Sub ComboBox1_DropDownClosed(sender As Object, e As EventArgs) Handles ComboBox1.DropDownClosed
Dim SelectedString As String = ComboBox1.SelectedItem.ToString
Dim ChangedString As String = SelectedString.Substring(0, 4)
Dim index As Integer = ComboBox1.SelectedIndex
ComboBox1.Items(index) = ChangedString
End Sub
You can fill your combo box one by one to avoid binding problems as follows...
Private Sub ComboBox1_DropDown(sender As Object, e As EventArgs) Handles ComboBox1.DropDown
Using cn As New SqlConnection("Your connection string")
Using cmd As New SqlCommand("Select ID, Name From tblFruit;", cn)
cn.Open()
Using dr As SqlDataReader = cmd.ExecuteReader
ComboBox1.BeginUpdate()
While dr.Read
ComboBox1.Items.Add(dr(0).ToString & " | " & dr(1).ToString)
End While
ComboBox1.EndUpdate()
End Using
End Using
End Using

You can solve this graphical problem putting a Label in your Form and moving it over your ComboBox.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.Label1.AutoSize = False
Me.Label1.BackColor = Me.ComboBox1.BackColor
Me.Label1.Location = New Point(Me.ComboBox1.Location.X + 1, Me.ComboBox1.Location.Y + 1)
Me.Label1.Size = New Size(Me.ComboBox1.Width - 18, Me.ComboBox1.Height - 2)
Me.ComboBox1.Items.Add("0001 | Apple")
Me.ComboBox1.Items.Add("0002 | Pear")
Me.ComboBox1.Items.Add("0003 | Banana")
Me.ComboBox1.Items.Add("0004 | Pineapple")
Me.ComboBox1.Items.Add("0005 | Cherry")
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Me.Label1.Text = Trim(Me.ComboBox1.SelectedItem.Split("|")(0))
End Sub
Please note that:
you can populate your ComboBox a single time during Form load event
you can use SelectedIndexChanged instead of DropDown and DropDownClosed event
if this is not a graphical problem please give a look at DisplayMember and ValueMember properties

Related

Strange behavior when setting null value in bound ComboBoxes

I prepared a small project demonstrating my issue. It consists of two data tables with a parent-child relation. I use vb.net 2010 with framework 4.0.
- Start a new WinForm project.
- On Form1 designer, drag one BindingNavigator, one Button and two ComboBoxes.
- In code behind, copy code below:
Public Class Form1
Private dsMain As DataSet
Private WithEvents bndSource As New BindingSource
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dsMain = New DataSet
'Create tables
Dim dtContacts As New DataTable("Contacts")
Dim col As DataColumn = dtContacts.Columns.Add("IDContact", GetType(Integer))
col.AllowDBNull = False
col.AutoIncrement = True
col.Unique = True
dtContacts.Columns.Add("FullName")
col = dtContacts.Columns.Add("IDCountry", GetType(Integer))
col.AllowDBNull = True
dsMain.Tables.Add(dtContacts)
Dim dtCountries As New DataTable("Countries")
col = dtCountries.Columns.Add("IDCountry", GetType(Integer))
col.AllowDBNull = False
col.AutoIncrement = True
col.Unique = True
dtCountries.Columns.Add("A2ISO")
dtCountries.Columns.Add("CountryName")
dsMain.Tables.Add(dtCountries)
'Add relation
Dim rel As New DataRelation("rel", dtCountries.Columns("IDCountry"), dtContacts.Columns("IDCountry"))
dsMain.Relations.Add(rel)
'Populate parent table
dtCountries.Rows.Add(1, "AF", "Afghanistan")
dtCountries.Rows.Add(2, "AL", "Albania")
dtCountries.Rows.Add(3, "DZ", "Algeria")
'Populate child table
dtContacts.Rows.Add(1, "First Contact", 3)
dtContacts.Rows.Add(2, "Second Contact", 1)
'Set bindings
bndSource.DataSource = dtContacts.DefaultView
BindingNavigator1.BindingSource = bndSource
ComboBox1.DataSource = dtCountries
ComboBox1.DisplayMember = "A2ISO"
ComboBox1.ValueMember = "IDCountry"
ComboBox1.DataBindings.Add("SelectedValue", bndSource, "IDCountry")
ComboBox2.DataSource = dtCountries
ComboBox2.DisplayMember = "CountryName"
ComboBox2.ValueMember = "IDCountry"
ComboBox2.DataBindings.Add("SelectedValue", bndSource, "IDCountry")
dsMain.AcceptChanges()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ComboBox1.Text = Nothing 'Set IDCountry to DBNull, same as ComboBox1.SelectedIndex = -1
ComboBox2.Text = Nothing
End Sub
End Class
- Run the project.
- Try to navigate back and forth, and change items in the ComboBoxes: all is correct.
- Now set IDCountry = Null in Contacts table, as it is allowed. To achieve this, click on Button1.
- In ComboBox1, if you select the same item as it was before clicking the button, you see the behavior is not correct anymore: ComboBox2 doesn't update accordingly with ComboBox1 but remains empty.
- If you select another item, from now on all is correct again.
Is this a bug in .net data binding? If so, is there any workaround?
Thanks in advance.
This is the workaround I found. I didn't find the reason of the behavior I observed, but this code works for me:
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
If ComboBox1.SelectedIndex < ComboBox2.Items.Count Then ComboBox2.SelectedIndex = ComboBox1.SelectedIndex
End Sub
Private Sub ComboBox2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox2.SelectedIndexChanged
If ComboBox2.SelectedIndex < ComboBox1.Items.Count Then ComboBox1.SelectedIndex = ComboBox2.SelectedIndex
End Sub
It simply makes ComboBox selected indexes equal.
Thank you anyway.

Datagridview and access database only updates after clicking a different row

I am reading an access database and populating the info in datagridview. My form has a DGV, and 3 buttons.
Button one copies the selected row to a datetimepicker control.
Button two copied the updated datetimepicker value back to the DVG
Button three does an update (writes the info back to the database).
My issue is that the info only gets updated in the database if I select a different row before hitting button three. I am not getting any error message in either case.
Below is my code. The database only has 2 columns (name and DOB - which is date/time).
Public Class Form1
Dim dbConn As New OleDb.OleDbConnection
Dim sDataset As New DataSet
Dim sDataAdapter As OleDb.OleDbDataAdapter
Dim sql As String
Dim iTotalRows As Integer
Dim sShipTypeFilter As String
Dim sBuildingFilter As String
Dim sCustSuppFilter As String
Dim sStatusFilter As String
Dim sDayFilter As String
Dim dv As New DataView
Sub myDBConn()
dbConn.ConnectionString = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\terry\Documents\Database1.accdb"
Debug.Print("Start:" & DateAndTime.Now.ToString)
dbConn.Open()
sql = "select * from TableX"
sDataAdapter = New OleDb.OleDbDataAdapter(Sql, dbConn)
sDataAdapter.Fill(sDataset, "MyTable")
dbConn.Close()
iTotalRows = sDataset.Tables("MyTable").Rows.Count
Debug.Print("Rows from Access:" & iTotalRows)
Debug.Print("End:" & DateAndTime.Now.ToString)
End Sub
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Call myDBConn()
Debug.Print("DVG1 row count before binding:" & DataGridView1.Rows.Count)
'dv = New DataView(sDataset.Tables(0), "Shipment = 'Regular' and Building = 'CSE'", "Company DESC", DataViewRowState.CurrentRows)
dv = sDataset.Tables(0).DefaultView
Debug.Print("DataView count:" & dv.Count)
DataGridView1.DataSource = dv
Debug.Print("DVG1 Rows:" & DataGridView1.Rows.Count)
DataGridView1.Columns("DOB").DefaultCellStyle.Format = "hh:mm tt"
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
dtp1.Value = DataGridView1.SelectedRows(0).Cells("DOB").Value
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
DataGridView1.SelectedRows(0).Cells("DOB").Value = dtp1.Value
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Debug.Print("switched row")
Me.Visible = False
Dim sqlcb As New OleDb.OleDbCommandBuilder(sDataAdapter)
sDataAdapter.Update(sDataset.Tables("MyTable"))
Me.Close()
End Sub
End Class
Before updating you need to Endedit. This means you need to add Endedit for the datagridview.
So this will be your code:
Debug.Print("switched row")
Me.Visible = False
Dim sqlcb As New OleDb.OleDbCommandBuilder(sDataAdapter)
Datagridview1.EndEdit()
sDataAdapter.Update(sDataset.Tables("MyTable"))
Me.Close()
EDIT1:
Dim dt As New DataTable
dbConn.Open()
sDataset.Tables.Add(dt)
sDataAdapter = New OleDbDataAdapter("Select * from TableX", dbConn)
sDataAdapter.Update(dt)
dbConn.Close()
I figured it out - thanks Stef for putting me on the right track.
My DGV is only updated programmatically (not by user edits) so I updated the code for button 2 to set the editmode, begin editing, update the selected DVG row and end editing:
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
DataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically
DataGridView1.BeginEdit(True)
DataGridView1.SelectedRows(0).Cells("DOB").Value = dtp1.Value
DataGridView1.EndEdit()
End Sub
After doing this modification - my datadapter.update command works!!

Selected index in ListBox dosent stay selected after getting values

I want to be able to select an index on my ListBox.My ListBox is getting getting values depending on the selected index, however when I try to select an index in the listbox, it gets the values but stays unselected. I have to select the index a second time for it to be selected. Why is that?
here is my code on the selectedIndexChanged:
Private Sub listResults_SelectedIndexChanged(sender As Object, e As EventArgs) Handles listResults.SelectedIndexChanged
UpdateContactInformationFromRegistry()
End Sub
The UpdateContactInformationFromRegistry() method:
Private Sub UpdateContactInformationFromRegistry()
Dim contact As Contact = m_contacts.GetContact(listResults.SelectedIndex)
cmbCountries.SelectedIndex = DirectCast(contact.AddressData.Country, Integer)
txtFirstName.Text = contact.FirstName
txtLastName.Text = contact.LastName
txtStreet.Text = contact.AddressData.Street
txtZip.Text = contact.AddressData.ZipCode
txtCity.Text = contact.AddressData.City
End Sub
UPDATE V2
cmbCountries.SelectedIndexChanged event handler
Private Sub cmbCountries_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbCountries.SelectedIndexChanged
UpdateGUI()
End Sub
UpdateGUI() method
Private Sub UpdateGUI()
Dim strContacts() As String = m_contacts.GetContactInfo()
If (strContacts IsNot Nothing) Then
listResults.Items.Clear()
listResults.Items.AddRange(strContacts)
lstCount.Text = listResults.Items.Count.ToString()
End If
End Sub

Public variable used for form opening not feeding through to from

Having some issues getting a form to populate based on a variable determined in current form.
I have a search result form that has a datagrid with all results, with an open form button for each row. When the user clicks this, the rowindex is used to pull out the ID of that record, which then feeds to the newly opened form and populates based on a SQL stored procedure run using the ID as a paramter.
However, at the moment the variable is not feeding through to the form, and am lost as to why that is. Stored procedure runs fine if i set the id within the code. Here is my form open code, with sci
Public Class SearchForm
Dim Open As New FormOpen
Dim data As New SQLConn
Public scid As Integer
Private Sub Search_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sql As New SQLConn
Call sql.SearchData()
dgvSearch.DataSource = sql.dt.Tables(0)
End Sub
Private Sub dgvSearch_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvSearch.CellContentClick
Dim rowindex As Integer
Dim oform As New SprinklerCardOpen
rowindex = e.RowIndex.ToString
scid = dgvSearch.Rows(rowindex).Cells(1).Value
TextBox1.Text = scid
If e.ColumnIndex = 0 Then
oform.Show()
End If
End Sub
End Class
The form opening then has the follwing:
Private Sub SprinklerCard_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Populate fields from SQL
Try
Call Populate.SprinklerCardPopulate(ID)
cboInsured.Text = Populate.dt.Tables(0).Rows(0).Item(1)
txtAddress.Text = Populate.dt.Tables(0).Rows(0).Item(2)
txtContactName.Text = Populate.dt.Tables(0).Rows(0).Item(3)
txtContactPhone.Text = Populate.dt.Tables(0).Rows(0).Item(4)
txtContactEmail.Text = Populate.dt.Tables(0).Rows(0).Item(5)
numPumps.Value = Populate.dt.Tables(0).Rows(0).Item(6)
numValves.Value = Populate.dt.Tables(0).Rows(0).Item(7)
cboLeadFollow.Text = Populate.dt.Tables(0).Rows(0).Item(8)
cboImpairment.Text = Populate.dt.Tables(0).Rows(0).Item(9)
txtComments.Text = Populate.dt.Tables(0).Rows(0).Item(10)
Catch ex As Exception
MsgBox(ex.ToString & "SCID = " & ID)
End Try
End Sub
Set the ID variable in the form before you open it.
If e.ColumnIndex = 0 Then
oform.ID = scid
oform.Show()
End If

Pass variable to new form with Datatable and Listbox

I am currently trying to write an application like address book. Listbox works properly, it shows everything corretly. But I need to pass id of chosen listbox item to another form. I got code like this in Form2:
Private myTable As New DataTable()
Public Sub LoadXml(sender As Object, e As EventArgs) Handles Me.Load
With myTable.Columns
.Add("DisplayValue", GetType(String))
.Add("HiddenValue", GetType(Integer))
End With
myTable.DefaultView.Sort = "DisplayValue ASC"
ListBox1.DisplayMember = "DisplayValue"
ListBox1.ValueMember = "HiddenValue"
ListBox1.DataSource = myTable
Dim doc As New Xml.XmlDocument
doc.Load("c:\address.xml")
Dim xmlName As Xml.XmlNodeList = doc.GetElementsByTagName("name")
Dim xmlSurname As Xml.XmlNodeList = doc.GetElementsByTagName("surname")
Dim xmlId As Xml.XmlNodeList = doc.GetElementsByTagName("id")
For i As Integer = 0 To xmlName.Count - 1
Dim nazwa As String = xmlName(i).FirstChild.Value + " " + xmlSurname(i).FirstChild.Value
myTable.Rows.Add(nazwa, xmlId(i).FirstChild.Value)
MsgBox(myTable.Rows(i).Item(1).ToString)
Next i
ListBox1.Sorted = True
End Sub
Later in the code I have event:
Public Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
End Sub
I would like to know how can I call id from DataTable for selected listbox item. I hope u understand what I mean since my english is not perfect :)
Since you have added the XML value id to the data table column HiddenValue and you have assigned HiddenValue as the ValueMember for the listbox, once a record is selected in the listbox, id will be available in the listbox's [SelectedValue][1] member. For example:
Public Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
MsgBox("Selected Id: " & ListBox1.SelectedValue.ToString())
End Sub