.NET WinForms。 ComBox <add new =“”>项目

时间:2017-02-25 05:46:19

标签: c# winforms

以下代码来自我的项目

using System;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;

namespace SmallOffice.Forms
{
    public class ComboBox : System.Windows.Forms.ComboBox
    {
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public new ObjectCollection Items
        {
            get
            {
                return base.Items;
            }
        }

        object addnew = "<Add new>";

        protected override void SetItemsCore(IList value)
        {
            List<object> list = new List<object>();
            for (int i = 0; i < value.Count; i++)
            {
                list.Add(value[i]);
            }
            list.Add(this.addnew);
            base.SetItemsCore(list);
        }

        protected override void OnBindingContextChanged(EventArgs e)
        {
            base.OnBindingContextChanged(e);

            if (DataSource != null)
            {
                this.manager = BindingContext[this.DataSource];
            }
        }

        System.Windows.Forms.BindingManagerBase manager;

        protected override void OnSelectedIndexChanged(EventArgs e)
        {
            base.OnSelectedValueChanged(e);

            // Here my ComboBox is becoming visibility dependent?
            // I don't think it is correct. This is wrong.
            // I can't find other way.
            if (Visible)
            {
                if (SelectedIndex == (Items.Count - 1))
                {
                    this.manager.AddNew();
                    this.manager.CancelCurrentEdit();
                }
            }
        }

    }
}

Everythink工作正常。问题是检查选择(OnSelectedIndexChanged)。在我的情况下,我在控件可见时检查选择。我认为这是错误的。如果有人做过像这样的ComboBox可以有人提出建议吗?

1 个答案:

答案 0 :(得分:0)

我相信您遇到的是在表单完成加载之前触发了您的事件,可能是由于数据绑定。这里有一个可能的问题解决方案:

https://stackoverflow.com/questions/3263240