.NET 3.5 (Visual Studio 2008) WinForms アプリケーションで読み取り専用モードの DataGridView を使用しています。
セルの幅は非常に小さいです。一部のセルに短い数値が含まれています。現在、小さなフォントでも、数字が省略記号で表示されることがあります。たとえば、 "88"ではなく"8..."です。
標準の DataGridView の次のセルにテキストを流し、省略記号を回避する方法はありますか?
ありがとう!
.NET 3.5 (Visual Studio 2008) WinForms アプリケーションで読み取り専用モードの DataGridView を使用しています。
セルの幅は非常に小さいです。一部のセルに短い数値が含まれています。現在、小さなフォントでも、数字が省略記号で表示されることがあります。たとえば、 "88"ではなく"8..."です。
標準の DataGridView の次のセルにテキストを流し、省略記号を回避する方法はありますか?
ありがとう!
DataGridView コントロールの CellPainting イベントを処理します。次のリンクを確認してください。
http://msdn.microsoft.com/en-us/library/hta8z9sz.aspx
テキスト自体を描画するときは、StringFormat をカスタマイズする必要があることに注意してください -
MSDN コードからの引用:
if (e.Value != null)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
Brushes.Crimson, e.CellBounds.X + 2,
e.CellBounds.Y + 2, StringFormat.GenericDefault);
}
StringFormat.GenericDefault の代わりに、次の StringFormat オブジェクトを使用します。
StringFormat strFormat = new StringFormat();
strFormat.Trimming = StringTrimming.None;
よろしく
ここで KD2ND によって提供された解決策は満足のいくものではありませんでした。このような小さな変更のためにセル ペインティングを完全に再実装するのはばかげているように思えます。列ヘッダーと選択された行のペインティングを処理するのも大変です。幸いなことに、よりきちんとした解決策があります。
// you can also handle the CellPainting event for the grid rather than
// creating a grid subclass as I have done here.
protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
{
var isSelected = e.State.HasFlag(DataGridViewElementStates.Selected);
e.Paint(e.ClipBounds, DataGridViewPaintParts.Background
//| DataGridViewPaintParts.Border
//| DataGridViewPaintParts.ContentBackground
//| DataGridViewPaintParts.ContentForeground
| DataGridViewPaintParts.ErrorIcon
| DataGridViewPaintParts.Focus
| DataGridViewPaintParts.SelectionBackground);
using (Brush foreBrush = new SolidBrush(e.CellStyle.ForeColor),
selectedForeBrush = new SolidBrush(e.CellStyle.SelectionForeColor))
{
if (e.Value != null)
{
StringFormat strFormat = new StringFormat();
strFormat.Trimming = StringTrimming.Character;
var brush = isSelected ? selectedForeBrush : foreBrush;
var fs = e.Graphics.MeasureString((string)e.Value, e.CellStyle.Font);
var topPos= e.CellBounds.Top + ((e.CellBounds.Height - fs.Height) / 2);
// I found that the cell text is drawn in the wrong position
// for the first cell in the column header row, hence the 4px
// adjustment
var leftPos= e.CellBounds.X;
if (e.RowIndex == -1 && e.ColumnIndex == 0) leftPos+= 4;
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
brush, leftPos, topPos, strFormat);
}
}
e.Paint(e.ClipBounds, DataGridViewPaintParts.Border);
e.Handled = true;
}
秘訣は、既存の `Paint メソッドにセルの大部分の描画を処理させることです。テキストの描画のみを処理します。境界線はテキストの後に描画されます。そうしないと、テキストが境界線の上に描画されることがあり、見栄えが悪いことがわかったからです。
いいえ、おそらく省略記号を無効にするプロパティがあります (基になるコントロールにアクセスする場合) が、標準の DataGridView ではフロー オーバー (およびセルのマージ) はサポートされていません。