【问题标题】:Remove padding/margin from DataGridView Cell从 DataGridView 单元格中删除填充/边距
【发布时间】:2011-02-16 13:30:31
【问题描述】:

我对 DataGridView 有疑问。默认单元格样式有一些边距或填充,使所有行都比我需要的高。

我将 RowTemplate 中的 Height 属性设置为较小的值(即 15 像素),但现在单元格会剪下下划线 ('_') 等较低的符号,并且单元格顶部有 1 或 2 个空白像素。

如何使 DataGridView 单元格显示没有填充/边距的值,如 ListView(详细视图)?

radzi0_0

【问题讨论】:

    标签: c# datagridview


    【解决方案1】:

    I am hoping that this goes some of the way to helping you in this situation;

    void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)//remove padding
    {
       // ignore the column header and row header cells
    
       if (e.RowIndex != -1 && e.ColumnIndex != -1)
       {
          e.PaintBackground(e.ClipBounds, true);
          e.Graphics.DrawString(Convert.ToString(e.FormattedValue), e.CellStyle.Font, Brushes.Gray, e.CellBounds.X, e.CellBounds.Y - 2, StringFormat.GenericDefault)
          e.Handled = true;
       }
    }
    

    【讨论】:

      【解决方案2】:

      我的 DataGridView 遇到了一些类似的问题。每次我调整列的大小时,我的字符串(例如“A”)都会被截断为“A...”,但字符串并没有伸出单元格。

      现在我刚刚发现字符串的边界有一些奇怪的行为。字符串周围有一个所谓的“布局矩形”,实际上比字符串本身大。这意味着如果矩形伸出可写区域(在本例中为 DataGridViewCell),则字符串将被截断或包裹。

      StringFormat format = new StringFormat(StringFormatFlags.NoClip);
      

      该对象提供了应该绘制字符串的信息,而这个讨厌的布局矩形不会太大。您可以使用 StringFormat,如 CodeBlend 所示。

      不幸的是,我没有找到一种方法将该对象分配给字符串,因此我不必关心字符串是如何绘制的。

      【讨论】: