如何隐藏DataGridView中某些列而不是所有列之间的行?

时间:2017-11-17 17:07:44

标签: c# winforms datagridview

是否可以仅隐藏winforms DataGridView中列的一些行?

myDataGridView.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal;隐藏整个网格上的垂直线,但是如何隐藏特定的垂直线?

1 个答案:

答案 0 :(得分:0)

DataGridView控件可以自定义到单个单元格 但是,它的定制可能有点棘手。

如果你想要一个自定义的单元格/列格式或行为,你必须构建一个覆盖内部机制的(它不是那么复杂)。

首先,创建一个自定义列/单元类,从它们的基类派生,然后设置新的默认属性。

由于您要在DataGridView列中显示位图,请构建一个:

public class MyCustomColumn : DataGridViewColumn
{
   public MyCustomColumn()
   {
      this.CellTemplate = new MyCustomCell();
      //Set the .ValueType of its Cells to Bitmap
      this.CellTemplate.ValueType = typeof(System.Drawing.Bitmap);
   }
}

然后定义Column Cells的新属性: 一些默认属性是必要的,以防止内部错误 创建新单元格。必须初始化默认图像。

public class MyCustomCell : DataGridViewImageCell
{
   public MyCustomCell()
      : this(true) { }

   public MyCustomCell(bool valueIsIcon)
   {
      //Set the .ImageLayout to "Zoom", so the image will scale
      this.ImageLayout = DataGridViewImageCellLayout.Zoom;
      //This is the pre-defined image if no image is set as Value. You can set this to whaterver you want.
      //Here I'm defining an invisible bitmap of 1x1 pixels
      this.Value = new System.Drawing.Bitmap(1,1);
      //This is an internal switch. Doesn't mean much here. Set to true to comply with the standard.
      this.ValueIsIcon = valueIsIcon;
   }

   public override DataGridViewAdvancedBorderStyle AdjustCellBorderStyle(
         DataGridViewAdvancedBorderStyle dataGridViewAdvancedBorderStyleInput,
         DataGridViewAdvancedBorderStyle dataGridViewAdvancedBorderStylePlaceHolder,
         bool singleVerticalBorderAdded,
         bool singleHorizontalBorderAdded,
         bool firstVisibleColumn,
         bool firstVisibleRow)
   {
      //Set the new values for these cells borders, leaving out the right one.
      dataGridViewAdvancedBorderStylePlaceHolder.Right = DataGridViewAdvancedCellBorderStyle.None;

      dataGridViewAdvancedBorderStyleInput.Top = DataGridViewAdvancedCellBorderStyle.Single;
      dataGridViewAdvancedBorderStylePlaceHolder.Bottom = DataGridViewAdvancedCellBorderStyle.Single;
      dataGridViewAdvancedBorderStyleInput.Left = DataGridViewAdvancedCellBorderStyle.Single;

      return dataGridViewAdvancedBorderStylePlaceHolder;
   }
}

最后,您实例化新列并将其添加到DataGridView的Columns集合中。 您可以将自定义列插入集合中的任何有效位置。

您可以将此代码放在Form_Load Event:

MyCustomColumn _MyColumn = new MyCustomColumn();
this.dataGridView1.Columns.Insert(2, _MyColumn);

当然,您可以设置任何其他属性以进一步自定义单元格格式。