设置ComboBox行间距(转)

 

虽然有许多第三方控件可以实现ComboBox行间距的设置,但有时候引用太多的第三方控件也是一件麻烦事。其实VisualStudio内置的ComboBox控件稍加控制也能实现“行间距设置”的效果。    
 
 //设置Comobox的行间距
        public static void cmbBind(ComboBox list, int itemHeight)
        {
            list.DropDownStyle = ComboBoxStyle.DropDownList;
            list.ItemHeight = itemHeight;
            list.DrawMode = DrawMode.OwnerDrawFixed;

            list.DrawItem += new DrawItemEventHandler(delegate(object sender, DrawItemEventArgs e)
            {
                if (e.Index < 0)
                {
                    return;
                }
                e.DrawBackground();
                e.DrawFocusRectangle();
                e.Graphics.DrawString(list.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y + 3);
            });
        }

    引用代码如下:
cmbBind(cmbDepartment, 20);   //此处cmbDepartment为ComboBox控件的Name属性,20为行间距

   当然,在这里,可能有些人会和我遇到同样一个问题:假使设置了ComboBox的DataSource属性后,例如:
            cmbDepartment.DataSource = DS_Temp.Tables["Department"];
            cmbDepartment.DisplayMember = "Department_Name";
            cmbDepartment.ValueMember = "Department_Name";

   以上代码会失效,所以,我们只能摒弃DataSource属性,利用循环来依次添加Items,例如:
            for (int i = 0; i < DS_Temp.Tables["Department"].Rows.Count; i++)
            {
                cmbDepartment.Items.Add(DS_Temp.Tables["Department"].Rows[i][0].ToString());
            
            }
posted @ 2013-12-09 22:29  bert.zeng  阅读(1371)  评论(0)    收藏  举报