Windows Forms: Adding Items To ListBox from TextBox in C#

How to Add items to ListBox from TextBox in C#

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "ListboxDemo" and then click OK

listbox c#

Step 2: Create a State class as below

public class States
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string Display
    {
        get
        {
            return string.Format("({0}) {1}", ID, Name);
        }
    }
}

Step 3: Design your form as below

c# listbox

Step 4: Add code to handle your form as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ListboxDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //Add item direct to listbox
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtValue.Text))
                return;
            listState.Items.Add(txtValue.Text);
            txtValue.Clear();
            txtValue.Focus();
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (listState.Items.Count > 0)
                listState.Items.RemoveAt(listState.SelectedIndex);
        }

        private void listState_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblValue.Text = listState.Text;
        }

        //Binding data to listbox
        private void btnLoadState_Click(object sender, EventArgs e)
        {
            List<States> list = new List<States>();
            list.Add(new States() { ID = "AL", Name = "Alabama" });
            list.Add(new States() { ID = "AZ", Name = "Arizona" });
            list.Add(new States() { ID = "CA", Name = "California" });
            listState.DataSource = list;
            listState.ValueMember = "ID";
            //listState.DisplayMember = "Name";
            listState.DisplayMember = "Display";
        }
    }
}

VIDEO TUTORIALS

 

Related Posts