开发者

Display Icon and string inside Cell in DataGridView

开发者 https://www.devze.com 2023-01-07 04:17 出处:网络
I have 2 variable I would like to display 开发者_如何学Pythonin one cell of a DataGridView. Icon stockIcon;

I have 2 variable I would like to display 开发者_如何学Pythonin one cell of a DataGridView.

Icon stockIcon; Int stockStatus;

I already looked at http://msdn.microsoft.com/en-us/library/7tas5c80.aspx But I think its way to complicated and don't show how to display to variables in one cell.

I don't need the ability to edit, only display the two variables.

Could someone provide me with a small example?

I work in C# 4.0 and its a System.Windows.Forms.DataGridView


Here is my own solution. Just set the Column type to LagerStatusColumn and it gets the job done.

 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);
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消