R.Tanaka.Ichiro's Blog

主にC# な話題です

目次

Blog 利用状況

ニュース

DataGridView のセルを自作する(その2)

http://blogs.wankuma.com/rti/archive/2007/06/07/79901.aspx
DataGridView のセルを自作する

の続きです。

予告通り

DataGridViewRColumn


DataGridViewRCell

を作ってみました。


using System.Windows.Forms;

public class DataGridViewRColumn : DataGridViewColumn
{
  public DataGridViewRColumn() {
    base.CellTemplate = new DataGridViewRCell();
  }
}

public class DataGridViewRCell : DataGridViewTextBoxCell {
  protected override void Paint(
    Graphics graphics,
    Rectangle clipBounds,
    Rectangle cellBounds,
    int rowIndex,
    DataGridViewElementStates cellState,
    object value,
    object formattedValue,
    string errorText,
    DataGridViewCellStyle cellStyle,
    DataGridViewAdvancedBorderStyle advancedBorderStyle,
    DataGridViewPaintParts paintParts)
  {
    base.Paint(
      graphics,
      clipBounds,
      cellBounds,
      rowIndex,
      cellState,
      "素敵だし爽やかRさん",
      formattedValue,
      errorText,
      cellStyle,
      advancedBorderStyle,
      paintParts
    );
  }
}


この列は、どんな値が入ろうとも、常に「素敵だし爽やかRさん」が表示されます(意味ねー)

ちなみに Paint メソッドが素敵なのは、引数が大量にもらえるところです。

例えば Graphics オブジェクトを使って以下のようなこともできます。


protected override void Paint(
  Graphics graphics,
  Rectangle clipBounds,
  Rectangle cellBounds,
  int rowIndex,
  DataGridViewElementStates cellState,
  object value,
  object formattedValue,
  string errorText,
  DataGridViewCellStyle cellStyle,
  DataGridViewAdvancedBorderStyle advancedBorderStyle,
  DataGridViewPaintParts paintParts)
{
  Image image = this.GetEditingControlImage(cellStyle, cellBounds, value);

  base.Paint(
    graphics,
    clipBounds,
    cellBounds,
    rowIndex,
    cellState,
    String.Empty,
    formattedValue,
    errorText,
    cellStyle,
    advancedBorderStyle,
    paintParts
  );
  graphics.DrawImageUnscaled(image, cellBounds.X, cellBounds.Y);

}

private Image GetEditingControlImage(DataGridViewCellStyle cellStyle, Rectangle cellBounds, object value) {
  MonthCalendar c = new MonthCalendar();
  c.Font = cellStyle.Font;

  if (this.Selected) {
    c.BackColor = cellStyle.SelectionBackColor;
    c.ForeColor = cellStyle.SelectionForeColor;
  }
  else {
    c.BackColor = cellStyle.BackColor;
    c.ForeColor = cellStyle.ForeColor;
  }
  
  Bitmap bmp = new Bitmap(cellBounds.Width, cellBounds.Height);
  c.DrawToBitmap(bmp, new Rectangle(0, 0, cellBounds.Width, cellBounds.Height));
  return bmp;      
}


ちょっと試しに書いてみただけなので、よく調べていないのですが、以下に2つ疑問があります。

(1) MonthCalendar って、どうして BackColor と ForeColor プロパティの値が反映されないの?
(2) Value を元にセルの高さと幅を調整しているみたいなんですが、サイズを無理やり固定化する方法って何かありませんか?

カスタム列ってことで、別に列と行のサイズを固定にしちゃっても良いんですけどね・・・

投稿日時 : 2007年6月8日 11:18

Feedback

No comments posted yet.
タイトル
名前
Url
コメント