Results 1 to 27 of 27

Thread: [RESOLVED] Add item to a combobox items collection at run time

Threaded View

  1. #15
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [RESOLVED] Add item to a combobox items collection at run time

    Personally, as a fan of data-binding, I would probably do it like this:
    vb.net Code:
    1. Public Class Form1
    2.  
    3.     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    4.         'Bind the settings collection via a BindingSource.
    5.         BindingSource1.DataSource = My.Settings.ComboBox1Items
    6.         ComboBox1.DataSource = BindingSource1
    7.     End Sub
    8.  
    9.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    10.         'Add a new item from a TextBox.
    11.         BindingSource1.Add(TextBox1.Text)
    12.     End Sub
    13.  
    14.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    15.         'Remove the selected item.
    16.         BindingSource1.RemoveCurrent()
    17.     End Sub
    18.  
    19. End Class
    Note that there's not actually a need for code like this:
    vb.net Code:
    1. If My.Settings.ComboBox1Items Is Nothing Then
    2.     ' Required only for first run.
    3.     My.Settings.ComboBox1Items = New Specialized.StringCollection
    4. End If
    When you add a StringCollection to your settings, note that the Value field is empty by default. That's what causes the setting property to be Nothing by default. If you edit the Value and add an item, notice that the Value field is populated with an XML snippet, which actually creates a StringCollection object. If you then edit again and remove the item, the XML remains. That way, your setting property will contain an empty StringCollection object by default and you never have to test for Nothing.
    Last edited by jmcilhinney; Jun 3rd, 2018 at 07:35 PM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width