How To Add Values To ListBox In C#

Adding values to a listbox is something really easy anyways if you don't know how to add values to a listbox then here you go.

You need to add these things to your project first of all
  1. Three buttons (add,show,clear)
  2. Listbox
  3. Textbox
Now arrange the things to look better , like this maybe(*_*)
preview buddy
After that time to code , just double click on button add which is button1 for me
//checking textbox1 for empty values or else add the values to listbox
            if(textBox1.Text == string.Empty)
            {
                MessageBox.Show("Come on enter some text", "Textbox empty");
            }
            else
            {
                listBox1.Items.Add(textBox1.Text);
                textBox1.Text = "";
            }
Then go for show button
 //checking for null values in listbox else display the message box lalalaalal
            if(listBox1.SelectedItem == null)
            {
                MessageBox.Show("select an item buddy", "select item");
            }
            else
            {
                MessageBox.Show(listBox1.SelectedItem.ToString());
            }
Finally clear button
//clearing the listbox items and setting textbox1 value to empty
            listBox1.Items.Clear();
            textBox1.Text = string.Empty;

Now all the parts are over, Full source below
 private void button1_Click(object sender, EventArgs e)
        {
            //checking textbox1 for empty values or else add the values to listbox
            if(textBox1.Text == string.Empty)
            {
                MessageBox.Show("Come on enter some text", "Textbox empty");
            }
            else
            {
                listBox1.Items.Add(textBox1.Text);
                textBox1.Text = "";
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
           //checking for null values in listbox else display the message box lalalaalal
            if(listBox1.SelectedItem == null)
            {
                MessageBox.Show("select an item buddy", "select item");
            }
            else
            {
                MessageBox.Show(listBox1.SelectedItem.ToString());
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //clearing the listbox items and setting textbox1 value to empty
            listBox1.Items.Clear();
            textBox1.Text = string.Empty;
        }
i hope it was somehow helpful , thank you

3 comments

Post a Comment

Note: Only a member of this blog may post a comment.