How to Add Items To ListBox from TextBox in C#

By FoxLearn 7/18/2024 7:39:49 AM   19.76K
To add items from a TextBox to a ListBox in a C# Windows Forms application, you can do the following step.

How to Add items to ListBox from TextBox in C#

Open your Visual Studio, then click 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

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);
        }
    }
}

Design your form as below

Drag and drop the TextBox, a ListBox, and a Button controls from the Visual Studio toolbox onto your form designer, then modify your layout as shown below.

c# listbox

Handle the click event of the button. In this event handler, you'll take the text from the TextBox and add it to the ListBox.

Add code to handle your form as below

//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);
}

In the Form_Load or in your form constructor you can initialize your data as shown below.

//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";
}

Add a SelectedIndexChanged event handler to the ListBox control allows you to get selected text.

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

Run your application and test the functionality. Enter text into the TextBox, click the button, and observe that the text is added to the ListBox.

VIDEO TUTORIAL

Related