C#自定义控件之下拉列表框

  1. 设置 DropDownStyle 为 DropDownList


     
  2. 将 DrawMode 改为 OwnerDrawFixed


     
  3. 添加 DrawItem 事件
  4.  样式就变为下面这样,但是只能在列表中选择,而不能手动输入

    public class ComBox : ComboBox
    {
        public ComBox()
        {
            this.DropDownStyle = ComboBoxStyle.DropDownList;
            this.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
            this.DrawItem += new DrawItemEventHandler(ComBox_DrawItem);
        }

        void ComBox_DrawItem(object sender, DrawItemEventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            if (e.Index < 0)
            {
                return;
            }
            e.DrawBackground();
            e.DrawFocusRectangle();
            e.Graphics.DrawString(cb.GetItemText(cb.Items[e.Index]).ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y + 3);
        }

    }
    public class CmbInfo
    {
        public int ID { get; set; }

        public object ObjEnum { get; set; }

        public string Name { get; set; }
    }


List<CmbInfo> listCmbInfo = new List<CmbInfo>();
listCmbInfo.Add(new CmbInfo() { ID = 100, Name = "100" });
listCmbInfo.Add(new CmbInfo() { ID = 120, Name = "120" });
listCmbInfo.Add(new CmbInfo() { ID = 150, Name = "150" });
this.cmb1.DisplayMember = "Name";
this.cmb1.ValueMember = "ID";
this.cmb1.DataSource = listCmbInfo;

//这样显示的是 Name 属性,取值时可以取 ID 属性 (this.cmb1.SelectedValue)
发布了31 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/breakbridge/article/details/87084532