用户控件的随想

最近在鼓弄winform的combobox控件

发觉还真的学到好多的呢 幸福ing~~~~

很多时候如果我们会在不同的页面中都使用相同的控件,并且他们的功能是一样地

那么 我们可以尝试把它做成一个用户控件

这样修改或者为其添加新的功能的话 会方便n百倍

下面贴下的我东东 一个实现可调整comboBox的下拉列表的大小的控件

1、项目添加用户自定义控件 取名CtrlComboBox 拖拽一个combobox控件

2、源码如下

 public partial class CtrlComboBox: ComboBox
    {
        public CtrlComboBox()
        {
            InitializeComponent();
        }
        protected override void OnDropDown(EventArgs e)
        {
            base.OnDropDown(e);
            AdjustComboBoxDropDownListWidth();  //调整comboBox的下拉列表的大小
        }

        private void AdjustComboBoxDropDownListWidth()
        {
            Graphics g = null;
            Font font = null;
            try
            {
                int width = this.Width;
                g = this.CreateGraphics();
                font = this.Font;

                             int vertScrollBarWidth =
                    (this.Items.Count > this.MaxDropDownItems)
                    ? SystemInformation.VerticalScrollBarWidth : 0;

                int newWidth;
                foreach (DataRowView  s in this.Items)  //Loop through list items and check size of each items.
                {
                    if (s != null)
                    {

                       newWidth = (int)g.MeasureString(s[1].ToString(), font).Width
                            + vertScrollBarWidth;
                        if (width < newWidth)
                            width = newWidth;   //set the width of the drop down list to the width of the largest item.
                    }
                }
                this.DropDownWidth = width;
            }
            catch
            { }
            finally
            {
                if (g != null)
                    g.Dispose();
            }
        }
    }

 

然后使用它就可以啦 不必再多次写重复代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值