How to set default selected item of listbox in winform c#?

10,943

Solution 1

Use a flag on the form/control to disable the event when you don't want it to fire.

public class Form1 : Form
{
    private bool itemsLoading;

    public Form1()
    {
        InitializeComponent();
        LoadListItems();
    }

    private void LoadListItems()
    {
        itemsLoading = true;
        try
        {
            listBox1.DataSource = ...
            listBox1.SelectedItem = ...
        }
        finally
        {
            itemsLoading = false;
        }
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (itemsLoading)
            return;

        // Handle the changed event here...
    }
}

Solution 2

don't add the selectedIndexChanged event until after you have changed the selectedItem to someObject ?

remove the event out of the form editor, or the designer.cs, and add it yourself manually by using the same code it auto generates?

Share:
10,943
Jennal
Author by

Jennal

C, C++, C#, Golang, Java, PHP, HTML/XHTML, CSS, Javascript, XML, XSLT, SCHEMA, Mysql, MS Sql, UML, Unity, electron

Updated on June 15, 2022

Comments

  • Jennal
    Jennal almost 2 years

    I try to set like this:

    ListBox lb = new ListBox();
    /* Bind datas */
    lb.SelectedItem = someObject;

    lb truely selected the someObject item. But it would select the 1st item at first. And that motion cause SelectedIndexChanged event which I don't wanted.

    I just want SelectedIndexChanged be called when someObject selected. How could I do to fix this?