我的C#Windows应用程序中有一个数据网格视图。 我需要更改单元格中最后5个字符的颜色,但我不知道该怎么做。
我在CellPainting事件中有这段代码,但是无效:
private void dgvSorteados_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
int sector = 0;
int.TryParse(dgvSorteados.Rows[e.RowIndex].Cells[0].Value.ToString(), out sector);
if (sector == 3 && rdbSenete3.Checked)
{
if (dgvSorteados.Columns[1].Index == e.ColumnIndex && e.RowIndex >= 0)
{
string bolillas = (String)e.Value;
string[] bolillasArray = bolillas.Split('-');
string bolillasMin = string.Join("-", bolillasArray.Take(12));
string bolillasResto = string.Join("-", bolillasArray.Skip(12));
using (Brush gridBrush = new SolidBrush(dgvSorteados.GridColor), backColorBrush = new SolidBrush(e.CellStyle.BackColor))
{
// Erase the cell.
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
// Draw the text content of the cell, ignoring alignment.
e.Graphics.DrawString((String)bolillasMin, e.CellStyle.Font, Brushes.Black, e.CellBounds.X + 2, e.CellBounds.Y + 2, StringFormat.GenericDefault);
if (!string.IsNullOrEmpty(bolillasResto))
{
e.Graphics.DrawString("-" + (String)bolillasResto, e.CellStyle.Font, Brushes.Crimson, e.CellBounds.X + 2 + bolillasMin.Length, e.CellBounds.Y + 2, StringFormat.GenericDefault);
}
e.Handled = true;
}
}
}
}
此代码显示没有行的DataGridView。
答案 0 :(得分:1)
您可以使用e.PaintBackground
调用来避免背景绘制代码。此外,您必须仅在绘制ContentForeGround
时绘制字符串。使用e.PaintParts
标识绘画操作。请参阅我的示例代码以了解其用法。它需要调整,但你会得到一个想法。
示例代码:
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex != -1 && e.Value != null && e.Value.ToString().Length > 5 && e.ColumnIndex == InterestedColumnIndex)
{
if (!e.Handled)
{
e.Handled = true;
e.PaintBackground(e.CellBounds, dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected);
}
if ((e.PaintParts & DataGridViewPaintParts.ContentForeground) != DataGridViewPaintParts.None)
{
string text = e.Value.ToString();
string textPart1 = text.Substring(0, text.Length - 5);
string textPart2 = text.Substring(text.Length - 5, 5);
Size fullsize = TextRenderer.MeasureText(text,e.CellStyle.Font);
Size size1 = TextRenderer.MeasureText(textPart1, e.CellStyle.Font);
Size size2 = TextRenderer.MeasureText(textPart2, e.CellStyle.Font);
Rectangle rect1 = new Rectangle(e.CellBounds.Location, e.CellBounds.Size);
using (Brush cellForeBrush = new SolidBrush(e.CellStyle.ForeColor))
{
e.Graphics.DrawString(textPart1, e.CellStyle.Font, cellForeBrush, rect1);
}
rect1.X += (fullsize.Width - size2.Width);
rect1.Width = e.CellBounds.Width;
e.Graphics.DrawString(textPart2, e.CellStyle.Font, Brushes.Crimson, rect1);
}
}
}