簡體   English   中英

為DataGridView單元格中的第一個字符設置顏色

[英]Set color for the first character in a cell of DataGridView

我是Winform C#的新手。 我有一個問題:有什么方法可以設置DataGridView單元格中第一個字符的顏色? 謝謝!

處理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;
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM