how to Add Items to a ListBox Control at runtime in C#

Following example add the contents of a TextBox control to a ListBox control when the Button control click. this example requires a windows form with Listbox control named ListBox1, one textbox control named TextBox1 and one Button control named button1 with Button1_Click event handler.

Example
[Vb.Net]

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
     ListBox1.Items.Add(TextBox1.Text.Trim()
End Sub

[C#]

private void Button1_Click(System.Object sender, System.EventArgs e)
{
ListBox1.Items.Add(TextBox1.Text.Trim());
}

if you want to avoid duplicate items in the listbox, we can search for a match before adding the contents of the TextBox to the Listbox with the help of items.Contains(val as object) method.

Example
[VB.Net]

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    If Not ListBox1.Items.Contains(TextBox1.Text.Trim()) Then
            ListBox1.Items.Add(TextBox1.Text.Trim())
    Else
        MessageBox.Show("text is already present in listbox")
    End If
End Sub

[C#]

private void Button1_Click(System.Object sender, System.EventArgs e)
  {
     if (!listBox1.Items.Contains(TextBox1.Text.Trim()))
       {
          listBox1.Items.Add(TextBox1.Text.Trim());
       }
    else
       {
          MessageBox.Show("text is already present in listbox");
        }
   }