开发者

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

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 wa开发者_JAVA百科nted.

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


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...
    }
}


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜