2010-07-13 74 views
3

我有2個變量我想在DataGridView的一個單元格中顯示。在DataGridView中顯示單元格內的圖標和字符串

Icon stockIcon; Int stockStatus;

我已經看過http://msdn.microsoft.com/en-us/library/7tas5c80.aspx但我認爲它的方式很複雜,並且不顯示如何在一個單元格中顯示變量。

我不需要編輯的能力,只顯示兩個變量。

有人能給我一個小例子嗎?

我的工作在C#4.0和一個System.Windows.Forms.DataGridView

+0

你確定它是一個單元嗎?爲什麼他們不能在兩個相鄰的列? – rotard 2010-07-13 14:50:04

+0

那麼它可能在兩個單元格中,但是可以執行單元格間距。因爲我只想要一個列標題。 「股票」 – gulbaek 2010-07-13 14:53:57

回答

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); 
     } 
    } 
} 
相關問題