动态适应DataGridViewComboBoxColumn的DropDownWidth

动态适应DataGridViewComboBoxColumn的DropDownWidth
DataGridView中的ComboBoxItems文字过长,显示不全对应策
        // ----------------------------------------------------
         ///   <summary>
        
///  BDataGridView cell enters edit mode 時発生します
        
///   </summary>
        
///   <param name="sender"></param>
        
///   <param name="e"></param>
         // ----------------------------------------------------
         private  void bDgvToti_EditingControlShowing( object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            ComboBox cmb = e.Control  as ComboBox;
             if (cmb !=  null)
            {
                cmb.DropDown -=  new EventHandler(bDgvCmb_DropDown);
                cmb.DropDown +=  new EventHandler(bDgvCmb_DropDown);
            }
        }

         // ----------------------------------------------------
         ///   <summary>
        
///  auto-size the DataGridViewComboBoxColumns's DropDownWidth
        
///   </summary>
        
///   <param name="sender"></param>
        
///   <param name="e"></param>
         // ----------------------------------------------------
         private  void bDgvCmb_DropDown( object sender,EventArgs e)
        {
            ComboBox cmb = sender  as ComboBox;
             int width = cmb.DropDownWidth;
            Graphics g = cmb.CreateGraphics();
            Font font = cmb.Font;
             int vertScrollBarWidth = 0;
             if (cmb.Items.Count > cmb.MaxDropDownItems)
                vertScrollBarWidth = SystemInformation.VerticalScrollBarWidth;

             int maxWidth;
             foreach (DataRowView drv  in cmb.Items)
            {
                 string s = drv[0].ToString();
                maxWidth = ( int)g.MeasureString(s, font).Width + vertScrollBarWidth;
                 if (width < maxWidth)
                    width = maxWidth;
            }

            DataGridViewComboBoxColumn c =
                 this.bDgvToti.Columns[bDgvToti.CurrentCell.ColumnIndex]  as DataGridViewComboBoxColumn;
             if (c !=  null)
                c.DropDownWidth = width;
        }

你可能感兴趣的:(动态适应DataGridViewComboBoxColumn的DropDownWidth)