【问题标题】:How to set default selected item of listbox in winform c#?如何在winform c#中设置列表框的默认选中项?
【发布时间】:2010-02-12 04:48:45
【问题描述】:

我尝试这样设置:

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

lb 确实选择了 someObject 项目。但它首先会选择第一项。而那个动作会导致我不想要的 SelectedIndexChanged 事件。

我只想在选择 someObject 时调用 SelectedIndexChanged。 我该怎么做才能解决这个问题?

【问题讨论】:

    标签: c# winforms listbox


    【解决方案1】:

    当您不想触发该事件时,使用表单/控件上的标志来禁用它。

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

    【讨论】:

      【解决方案2】:

      在将 selectedItem 更改为 someObject 之前不要添加 selectedIndexChanged 事件?

      从表单编辑器或 Designer.cs 中删除事件,然后使用它自动生成的相同代码手动添加?

      【讨论】:

        猜你喜欢
        • 2019-08-05
        • 1970-01-01
        • 2019-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-17
        • 2013-06-02
        • 2014-06-25
        相关资源
        最近更新 更多