2016-10-13 4 views
0

Winform C#を初めて使用しています。私は質問がある:DataGridViewのセル内の最初の文字の色を設定する方法はありますか? ありがとうございました!DataGridViewのセルの最初の文字の色を設定します。

+0

いいえ、CellPaintingイベントでセルをオーナー描画する必要があります。 – TaW

+0

あなたの提案をありがとう、私はこれを試してみよう! @TaW – quokka

答えて

0

CellPaintingイベントを処理するのが正しい方法です。グリッド列見出しを除いた特定のセルに要件を適用するコードスニペットを次に示します。

private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) 
{ 
    if (e.Value != null && !string.IsNullOrEmpty(e.Value.ToString()) && e.RowIndex != -1) 
    { 
     // Current cell pending to be painted. 
     var currentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]; 
     // Cell that needs to be painted. In this case the first cell of the first row. 
     var cellToBePainted = dataGridView1.Rows[0].Cells[0]; 

     if (currentCell == cellToBePainted) 
     { 
      using (Brush customColor = new SolidBrush(Color.Red)) 
      using (Brush cellDefaultBrush = new SolidBrush(e.CellStyle.ForeColor)) 
      { 
       string fullText = e.Value.ToString(); 
       string firstChar = fullText[0].ToString(); 
       string restOfTheText = fullText.Substring(1); 

       e.PaintBackground(e.CellBounds, true); 
       Rectangle cellRect = new Rectangle(e.CellBounds.Location, e.CellBounds.Size); 
       Size entireTextSize = TextRenderer.MeasureText(fullText, e.CellStyle.Font); 

       Size firstCharSize = TextRenderer.MeasureText(fullText[0].ToString(), e.CellStyle.Font); 
       e.Graphics.DrawString(fullText[0].ToString(), e.CellStyle.Font, customColor, cellRect); 

       if (!string.IsNullOrEmpty(restOfTheText)) 
       { 
        Size restOfTheTextSize = TextRenderer.MeasureText(restOfTheText, e.CellStyle.Font); 
        cellRect.X += (entireTextSize.Width - restOfTheTextSize.Width); 
        cellRect.Width = e.CellBounds.Width; 
        e.Graphics.DrawString(restOfTheText, e.CellStyle.Font, cellDefaultBrush, cellRect); 
       } 

       e.Handled = true; 
      } 
     } 
    } 
} 
+0

ありがとう、私が特定の細胞を申請したいのであれば、私は何を変更できますか? – quokka

+0

ハンドラ内の現在のセルは、次のように取得できます。var currentCell = dataGridView1.Rows [e.RowIndex] .Cells [e.ColumnIndex]; –

+0

私は最初の答えを更新して、特定のセルを確認しました。 –

関連する問題