ComboBox Control for VB.NET
Here is some example of ComboBox in visual basic VB.NET. We show you how to add and delete items with some basic tips. Most codes are self-explanatory.
A project sample is available to download at the end of this post. Free to download.
Using a TextBox: Add Item in ComboBox
From the project example available at the end of this post, I made a simple Button1 that adds a String from a TextBox1. The method checks the TextBox1 value before adding it the ComboBox1. The TextBox clears at the end.
If the ComboBox1 contains the value, then the TextBox1 is highlighted. This way, we tell the user to change the entry.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 'Add values in ComboxBox1 'will not add if value exist in ComboBox If TextBox1.Text IsNot Nothing Then If TextBox1.Text.Length > 0 Then If Not ComboBox1.Items.Contains(ComboBox1.Text) Then ComboBox1.Items.Add(TextBox1.Text) TextBox1.Text = "" Else TextBox1.SelectionStart = 0 TextBox1.SelectionLength = TextBox1.Text.Length End If End If End If End Sub |
Using a Button: Delete item in ComboBox
SelectedIndex could be minus one if nothing is selected. So we always have to make sure the SelectedIndex for a ComboBox is valid. If you are using the ComboBox with the default specifications, try to no use SelectedValue, SelectedText or SelectedItem. Be advare that ComboBox1 Dot Text is the visible text inside the ComboBox1. That text is not inside the ComboBox1 collection.
In the sample, I use the RemoveAt to delete the current Selected Index. Deleting the ComboBox1 dot text is a nice to have.
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click 'Delete a value in ComboBox1 If ComboBox1.SelectedIndex >= 0 Then ComboBox1.Items.RemoveAt(ComboBox1.SelectedIndex) End If If ComboBox1.Items.Count = 0 Then ComboBox1.Text = "" End If End Sub |
Add item in ComboBox using Keyboard
You need to use the KeyEventArgs. I choose the KeyUp event because I think is better than the KeyDown.
The KeyUp work the same way than my previous example with my Button1. Again, I do basic checking before adding the String value.
Private Sub ComboBox1_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles ComboBox1.KeyUp 'pressing Enter will add the text in the ComboBox1 Collection 'will not put duplicate values (case true) If e.KeyCode = Keys.Enter Then If ComboBox1.Text.Length > 0 Then If Not ComboBox1.Items.Contains(ComboBox1.Text) Then ComboBox1.Items.Add(ComboBox1.Text) ComboBox1.Text = "" Else ComboBox1.SelectionStart = 0 ComboBox1.SelectionLength = ComboBox1.Text.Length End If End If End If End Sub |
SQL Server Developer Edition 2012
0 Response to "ComboBox Control for VB.NET "
Posting Komentar