我想在DataGridView的一个单元格中显示2个变量。
Icon stockIcon; Int stockStatus;
我已经看过http://msdn.microsoft.com/en-us/library/7tas5c80.aspx但我认为它很复杂,并没有显示如何在一个单元格中显示变量。
我不需要编辑功能,只显示两个变量。
有人能为我提供一个小例子吗?
我使用的是C#4.0及其System.Windows.Forms.DataGridView
答案 0 :(得分:4)
这是我自己的解决方案。只需将Column类型设置为LagerStatusColumn即可完成工作。
public class LagerStatusColumn : DataGridViewColumn
{
public LagerStatusColumn()
{
CellTemplate =
new LagerStatusCell();
ReadOnly = true;
}
}
public class LagerStatusCell : DataGridViewTextBoxCell
{
protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.Drawing.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, value, "", errorText, cellStyle,
advancedBorderStyle, paintParts);
var cellValue = Convert.IsDBNull(value) ? 0 : Convert.ToDecimal(value);
const int horizontaloffset = 2;
var parent = (LagerStatusColumn)this.OwningColumn;
var fnt = parent.InheritedStyle.Font;
var icon = Properties.Resources.lager;
if (cellValue == 0)
icon = Properties.Resources.rest;
else if (cellValue < 0)
icon = Properties.Resources.question_white;
const int vertoffset = 0;
graphics.DrawIcon(icon, cellBounds.X + horizontaloffset,
cellBounds.Y + vertoffset);
var cellText = formattedValue.ToString();
var textSize =
graphics.MeasureString(cellText, fnt);
// Calculate the correct color:
var textColor = parent.InheritedStyle.ForeColor;
if ((cellState &
DataGridViewElementStates.Selected) ==
DataGridViewElementStates.Selected)
{
textColor = parent.InheritedStyle.
SelectionForeColor;
}
// Draw the text:
using (var brush = new SolidBrush(textColor))
{
graphics.DrawString(cellText, fnt, brush,
cellBounds.X + icon.Width + 2,
cellBounds.Y + 0);
}
}
}