Thursday 5 June 2014

Add item to listbox from textbox in c#.net

Add item to listbox from textbox in c#.net

In this post I will show you how to add item to listbox from textbox in c#.net. For this purpose start visual studio and create a new windows form application. This example requires a form with a listbox control name listbox1(or whatever you want), a textbox and 3 buttons with names –
Button1 = Add
Button2 = Clear List
Button3 = Remove Selected
Now arrange the control to look better like this :



Now your add button divides into 4 parts.
First of all check for duplicate values in listbox and give an already exist message.
if textbox’s value not found in listbox add it.
Clear textbox.
And focus on textbox.
For this purpose double click on add button and paste highlight code showing below.

private void button1_Click(object sender, EventArgs e)
        {
            if (listBox1.Items.Contains(textBox1.Text.ToString()) == false)
            {
                listBox1.Items.Add(textBox1.Text.Trim().ToString());
                textBox1.Clear();
                textBox1.Focus();
            }
            else
            {
                MessageBox.Show("Name already exist");
            }
        }

Now double click on clear button and paste highlight code

private void button2_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
        }

Now double click on delete selected button and paste highlight code

private void button3_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > 0)
            {                            
                listBox1.Items.Remove(listBox1.SelectedItem);
            }
            else
            {
                MessageBox.Show("Please select an item to remove");
            }
        }


Now press F5 or Go to Debug -> Start Dubbing and see output.


Share this post
  • Share to Facebook
  • Share to Twitter
  • Share to Google+
  • Share to Stumble Upon
  • Share to Evernote
  • Share to Blogger
  • Share to Email
  • Share to Yahoo Messenger
  • More...

0 comments:

Post a Comment