ComboBox default item - vb.net

I'm writing a simple program in VB with WinForms (well, I guess so, as I have never tried anything like that before). My google-driven development attempt was going pretty well until I tried to make a ComboBox control show one of its items by default.
So there is ComboBox1 with two items ("Item A" and "Item B") added through graphical interface (property Items in Properties panel). I go to Form1_Load event description in the code window and add the following line:
ComboBox1.SelectedItem = 0
That is supposed to make "Item A" the default item preselected when the program starts. But it doesn't work. What am I doing wrong?

That's because you are using 0(an integer) on ComboBox.SelectedItem, but ComboBox.Selected item is not an index to an element, it's an actual object.
This is how you use ComboBox.SelectedItem:
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBox1.Items.Add("Item A")
ComboBox1.Items.Add("Item B")
ComboBox1.SelectedItem = "Item A"
End Sub
End Class

Related

Event is triggered when I do not want it

I have a question about the behavior of the combobox, more precisely about the Selected-Index-Changed-Eventhandler.
In this test project, I click on the first entry in the Combobox. Correctly, “Something happening here” appears in the output window below. But if I click on the same entry again, the event will be triggered again. That is not supposed to happen. Is there a trick to prevent this from happening? I would only think of creating a variable (oldIndex) and comparing the current index with the old one.
Edit
Public NotInheritable Class FormMain
Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBox1.Items.AddRange({"1", "2", "3"})
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If ComboBox1.SelectedIndex <> (-1) Then
Debug.WriteLine("Something hapening here")
Select Case ComboBox1.SelectedIndex
Case 0
TextBox1.Text = "1"
Case 1
TextBox1.Text = "2"
Case 2
TextBox1.Text = "3"
Case Else
Exit Select
End Select
End If
End Sub
End Class
The implementation of the SelectedIndex property actually prevents these spurious events already but it appears that selecting an item via the UI doesn't actually cause the SelectedIndex property to be set. What we can do is inherit the ComboBox class and track the SelectedIndex ourselves and then simply abort the SelectedIndexChanged event if the property value hasn't actually changed:
Public Class ComboBoxEx
Inherits ComboBox
Private _selectedIndex As Integer = Integer.MinValue
Protected Overrides Sub OnSelectedIndexChanged(e As EventArgs)
If _selectedIndex = SelectedIndex Then
'The selection hasn't actually changed.
Return
End If
_selectedIndex = SelectedIndex
MyBase.OnSelectedIndexChanged(e)
End Sub
End Class
If you add a new class to your project, add that code and then build, the new control will appear in your Toolbox. You can then add it to a form instead of a regular ComboBox. If you already have a form with a regular ComboBox on it then you can open the designer code file and change the type of the existing controls. Make sure you have a backup first, in case you make a mistake and kill your form.
There are a couple of points to note here. Firstly, the SelectionChangeCommitted event behaves the same way, so you probably ought to override the corresponding method too. If you're not using that event though, it's not too important. This code does take care of the SelectedValueChanged event though.
Secondly, I'm not sure whether there might be times when this code could cause issues, e.g. the actual item selection has changed but the SelectedIndex hasn't. Probably not an issue but something to consider.

vb.net ComboBox Text Changing When Left

I'm having an issue with my ComboBoxes whereby if I type into it to get a value & then tab out the Text changes to the first item in the list with the first letter typed.
I have:
AutoCompleteMode set to SuggestAppend
AutoCompleteSource set to ListItems
DropDownStyle set to DropDownList
I add the items for the ComboBox in the Load event of the Form the ComboBox is on.
e.g. the below is code from a Load event where I populate a ComboBox that I have set up as below.
`Me.ComboBox1.Text = ""
Me.ComboBox1.Items.Add("a")
Me.ComboBox1.Items.Add("aaa")
Me.ComboBox1.Items.Add("combo")
Me.ComboBox1.Items.Add("combobox")
Me.ComboBox1.Items.Add("combobox test")
Me.ComboBox1.Items.Add("common")
Me.ComboBox1.Items.Add("common dialog")`
After running the code, if I select the ComboBox1 & type in common - common is selected in ComboBox1 but if I leave ComboBox1 the Text reverts to combo.
It gets a bit stranger as if I user the below code in the ComboBox1_Leave event procedure it throws common:
MsgBox(ComboBox1.Text)
I've also tried assigning the value of Text to a string in the ComboBox1_KeyUp event procedure & then assign that to ComboBox1.Text in the ComboBox1_Leave event procedure but that doesn't do anything.
If I put a the above MsgBox code before assigning the strings value to ComboBox1.Text then the Text value does revert to Common but this is isn't a practical solution.
I've also noticed that if I hit Enter before hitting tab it retains the correct value but again I'm don't think this is a particularly practical solution.
Does anyone have any idea what's going on here & how I can fix it?
It is absolutely necessary to have the DropDownStyle set to DropDownList?
Because if you set DropDownStyle to DropDown the selected value will be retained when you press tab or lose the focus.
If it's absolutely necessary to have it that way, you could try this.
Public Class Form2
Dim selectedTextForCombo As String = ""
Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.ComboBox1.Text = ""
Me.ComboBox1.Items.Add("a")
Me.ComboBox1.Items.Add("aaa")
Me.ComboBox1.Items.Add("combo")
Me.ComboBox1.Items.Add("combobox")
Me.ComboBox1.Items.Add("combobox test")
Me.ComboBox1.Items.Add("common")
Me.ComboBox1.Items.Add("common dialog")
End Sub
Private Sub ComboBox1_LostFocus(sender As Object, e As System.EventArgs) Handles ComboBox1.LostFocus
ComboBox1.SelectedItem = selectedTextForCombo
'This is just for a visualization of your issue
'Label1.Text = selectedTextForCombo
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
selectedTextForCombo = ComboBox1.Text
'This is just for a visualization of your issue
'Label1.Text = selectedTextForCombo
End Sub
End Class
Warning:
This example works with the tab action.
If the users writes something that doesn't exist like "commun" the
selected value will end up being the visually selected value, in this
case: "common"

Basic solution for adding list item to combo box via code on load

What I need:
I was a basic equivalent of a select box i.e. a combobox of dropdown list style (that preferably doesn't allow text input).
I need to add the list items by code rather than the property box.
What I have:
Private Sub Form_Load ()
ComboStaffMember.AddItem "John Murphy"
End Sub
...produces "...add item is not a member of system.windows.forms.comboxbox".
Private Sub Form_Load ()
ComboStaffMember.Items.Add("John Murphy")
End Sub
...produces no result.
My question:
Why is the item not adding? The form name is FrmStaffLogIn and it's in Form1.vb. Should Form_Load correspond to either of these or is my code incorrect elsewhere?
Try to put combo add statement in following format in form load event :
Private Sub Form_Load ()
Me.ComboStaffMember.Items.Add(New DictionaryEntry("Text to be displayed", 1))
End Sub
Are you sure your code line ComboStaffMember.Items.Add("John Murphy") doesn't work? it should work just fine.
The Add() method On Item collection expects object parameter and string as well can be passed as argument to it. Like below [C# code sample]:
this.comboBox1.Items.AddRange(
new string[] {"SomeText","SomeOtherText","LastText"});
Also, you probably don't see any item cause you haven't set a default selected item. Just expand the dropdown and you will see the items. To set the default selected item
this.comboBox1.SelectedIndex = 0;
Working code:
Private Sub FrmIdentCust_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboStaffMember.Items.Add("John Murphy")
End Sub
I was missing (sender As Object, e As EventArgs) Handles MyBase.Load.

Adding Objects with Display Text to ComboBox and Selecting Them

First it is worth it to note that I am very new to Visual Basic. I have created a win forms project in Visual Studio 2012 in the Visual Basic Language.
Given the below code, I want to use a combobox named cmbChoose to select from 4 options. These options will be listed in the combobox as:
"Problem 1"
"Problem 2"
"Problem 3"
"Problem 4"
When a user changes the index of cmbChoose, I would like the class object associated with that index to be set to a parent class object to get polymorphic behavior. A flow of this might be:
User selects "Problem 1".
Parent object problem is set to the class object stored at the index of "Problem 1". This object will be problem1 which is created at the top of the class.
User performs actions, problem1 is the current subclass executing functions
User selects "Problem 3".
Parent object problem is set to the class object stored at the index of "Problem 1". This object will be problem3 which is created at the top of the class.
It seems very simple, and I've read on several posts on stackOverflow to try to get the syntax correct, but I'm doing something wrong. I've made sure the combobox can "Use data bound items", and I've tried to set the DataSource, DisplayMember, and ValueMember in different ways. I've tried to access the object stored at a index in different ways.
I do not want to use conditionals to choose the object, it must be the object at the index chosen.
Here is the code. Assume the Problem classes and subclasses are correctly coded (they are). The functions that will need to be changed/implemented correctly are:
Frm_Base_Load() *or another appropriate function to load the combobox
cmbChoose_SelectedIndexChanged()
Public Class Frm_Base
Private problem As Problem
Private problem1 As Problem1 = New Problem1()
Private problem2 As Problem2 = New Problem2()
Private problem3 As Problem3 = New Problem2()
Private problem4 As Problem4 = New Problem2()
Private Sub btnQuit_Click(sender As Object, e As EventArgs) Handles btnQuit.Click
End
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
lstTable.Items.Clear()
End Sub
Private Sub btnDoWhile_Click(sender As Object, e As EventArgs) Handles btnDoWhile.Click
problem.DoWhile()
End Sub
Public Sub btnDoUntil_Click(sender As Object, e As EventArgs) Handles btnDoUntil.Click
problem.DoUntil()
End Sub
Public Sub btnForNext_Click(sender As Object, e As EventArgs) Handles btnForNext.Click
problem.Fornext()
End Sub
Private Sub Frm_Base_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Need to implement
'cmbChoose.DataSource = problem1
'cmbChoose.DisplayMember = "Problem 1"
'cmbChoose.ValueMember = 0
End Sub
Private Sub cmbChoose_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbChoose.SelectedIndexChanged
'Need to change to set parent object 'problem' to sub object at current index
problem = cmbChoose.DataSource
End Sub
End Class
Alright, asuming your Classes are correct this is what you have to do:
In Form_Load:
First create list of Problem
Dim ProbList As New List(Of Problem)
Then add all problems to that List.
ProbList.Add(ProblemX)
Then create a binding source and add the list as datasource
Dim BSProblems As New BindingSource
BSProblems.DataSource = ProbList
Then add the Bindingsource to the combobox.
ComboBox.DataSource = BSProblems
Then add whatever display member you want (I have selected Name, you probably have something different).
ComboBox.DisplayMember = "Name"
Then, in your Problem class you would have to have a property called Name. You create a property like this:
Property Name As String
Notice how it does not say "Public Name..." since that doesn't work (this is a common mistake here).
Finally you have to fetch the Problem base class from SelectedIndexChanged:
problem = CType(ComboBox.SelectedItem, Problem)
Hope this helps you out. Note that the only reason I help you this much is because I had a hard time understanding this myself. Don't expect this kind of help in the future since it does not look like you have tried that many things before posting this question.

VS 2010 VB.net create listbox as class

I have a Form1 in this Form1 I have created basic Common Controls like a listbox, a Combobox etc.
What I would like to do is to create a Button Click event that will create a new set of all these "Common Controls" like a new Class item, so that they are created below the first set.
Before Button(Add new) is pressed
"Combobox1" "ListBox1" "Textbox1"
Button(Delete this Item)
After Button(Add new) is pressed 2 times in row:
Button(Add new)
"Combobox1" "ListBox1" "Textbox1"
Button(Delete this Item)
"Combobox2" "ListBox2" "Textbox2"
Button(Delete this Item)
"Combobox3" "ListBox3" "Textbox3"
Button(Delete this Item)
Any hints on how to do this?
I will presume you are looking to learn vb.net, Here is a good article to start with
http://www.tutorialspoint.com/vb.net/vb.net_listbox.htm
the code for an event triggered by a button click is
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsgBox("You have clicked a button")
End Sub
you'll have to create a brand new class that generates documents (stream writers if i remember correctly) and then record everything in strings, make sure to have loops, give input places so you actually can give an ID for each of these controls.