重写ComboBox,使其自适应DropDownList中最长一个Item的Width

重写ComboBox,使其自适应DropDownList中最长一个Item的Width
        // -----------------------------------------------------------
         ///   <summary>
        
///  DropDown時発生します。
        
///   </summary>
         // -----------------------------------------------------------
         protected  override  void OnDropDown(EventArgs e)
        {
             this.BackColor = backColor;
            AdjustDropDownWidth();
             base.OnDropDown(e);
        }

         // -----------------------------------------------------------
         ///   <summary>
        
///  AdjustDropDownWidth
        
///   </summary>
         // -----------------------------------------------------------
         private  void AdjustDropDownWidth()
        {
            Graphics g =  this.CreateGraphics();
            Font font =  this.Font;
             string str = "";
             int width =  this.Width;
             int vScrollWidth = 0;
             int newWidth = 0;

             try
            {
                vScrollWidth = ( this.Items.Count >  this.MaxDropDownItems) ?
                    SystemInformation.VerticalScrollBarWidth : 0;

                 foreach ( object s  in  this.Items)
                {
                     if (s !=  null)
                    {
                         if ( this.DataSource ==  null)
                            str = s.ToString();
                         else  if (s  is DataRow)
                            str = ((DataRow)s)[ this.DisplayMember].ToString();
                         else  if (s  is DataRowView)
                            str = ((DataRowView)s)[ this.DisplayMember].ToString();
                         else
                            str = " ";

                        newWidth = ( int)g.MeasureString(str.ToString().Trim(), font).Width + vScrollWidth;
                         if (width < newWidth)
                            width = newWidth;
                    }
                }
                 this.DropDownWidth = width;
            }
             catch (Exception e)
            {
                 throw e;
            }
             finally
            {
                 if (g !=  null)
                    g.Dispose();
            }
        }

你可能感兴趣的:(重写ComboBox,使其自适应DropDownList中最长一个Item的Width)