Saturday, May 7, 2016

Program 4: Create a windows form to add the items to the ListBox and remove them by using buttons.


1. Open Visual studio 2013.
2. On the menu bar, choose File, New, and Project. Choose Programming language as  Visual C# . In the 
    templates list, choose the Windows Forms Application icon.
3.  Name the project as ListboxExample and specify the address of your folder.
4. In the main window design the form as shown below. 

Here, the listbox is named as lstbox. Two buttons are used such as Add and Remove. the names of the buttons are btnAdd and btnRemove respectively. Code for both these buttons is given below. 

use the following code.

List<string> items = new List<string>();

        public Form4()
        {
            InitializeComponent();
            items.Add("One"); // <-- add="" span="" these="">
            items.Add("Two");
            items.Add("Three");

            lstbox.DataSource = items;
        }
        
        private void btnAdd_Click(object sender, EventArgs e)
        {
            // The Add button was clicked.
            items.Add("New item " + DateTime.Now.Second); // <-- any="" span="" string="" want="" you="">

            // Change the DataSource.
            lstbox.DataSource = null;
            lstbox.DataSource = items;
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            int selectedIndex = lstbox.SelectedIndex;

            try
            {
                // Remove the item in the List.
                items.RemoveAt(selectedIndex);
            }
            catch
            {
            }

            lstbox.DataSource = null;
            lstbox.DataSource = items;
        }
3.     Run your program  and check the result

No comments:

Post a Comment