We help IT Professionals succeed at work.

Retrieving SelectedValue from ComboBox programmatically?

BlakeMcKenna
BlakeMcKenna asked
on
Ok,

Here is a strange request but I am not really sure how to do this. I have a ComboBox (CB) that has two items in it. It's a DataBound CB so it has ValueMember/DisplayMember properties set. There is a default value selected. When certain processing is done within the app, the SelectedValue needs to change to the other Item in the CB without the user manually selecting it. Is there a way of Looping through the CB's Items?

Thanks!
Comment
Watch Question

Éric MoreauSenior .Net Consultant
Top Expert 2016

Commented:
you can loop through the items property
Senior .Net Consultant
Top Expert 2016
Commented:
Do you have the value of the other ValueMember? In that case, you can just set the SelectedValue property:

Public Class Form1

	Private mdt As DataTable

	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
		FillCombo()
	End Sub

	Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
		ComboBox1.SelectedValue = 3
	End Sub

	Private Sub FillCombo()
		mdt = New DataTable("test")
		With mdt
			.Columns.Add("ID", GetType(Integer))
			.Columns.Add("Description", GetType(String))

			For i As Integer = 1 To 5
				.Rows.Add(New Object() {i, "Row " + i.ToString()})
			Next
		End With

		ComboBox1.DataSource = mdt
		ComboBox1.ValueMember = "ID"
		ComboBox1.DisplayMember = "Description"
	End Sub
End Class

Open in new window

Author

Commented:
I do have the other ValueMember, however, I want to keep it as dynamic as possible. I'd rather not hard-code anything because the ValueMember values come from a Database.
Éric MoreauSenior .Net Consultant
Top Expert 2016

Commented:
I don't mean to hardcode. You can surely retrieve the second value and use it to set the selectedvalue property. You could also set the selectedindex property which is the position

Author

Commented:
Eric,

I found a solution. I actually add the ValueMember (the primary key) to an array variable when the CB was first loaded. At the point when I need to change the value, I simply looped thru the 2 element array and chose the other value. It's rude and crude but it works.

Thanks for your posts!

Author

Commented:
Thanks again for your input!
Éric MoreauSenior .Net Consultant
Top Expert 2016

Commented:
Is the combobox the ideal solution if you have only 2 values? wouldn't 2 option buttons be better?

Author

Commented:
Using Option Buttons would make sense with the way things are now, however, since it is database driven, it is conceivably possible for there to be more than two values. If that were the case, then I would need to create these controls dynamically on the form and unfortunately the real estate is pretty tight.