1

VB .NET では、いくつかの計算に応じて DataGridView セルに追加される 3 つの文字があります。

それらはランク変更の矢印であり、正常に機能しますが、上向きの矢印を緑に、下向きの矢印を赤にしたいと思います。

Dim strup As String = "▲"
Dim strdown As String = "▼"
Dim strsame As String = "▬"

したがって、セルでは、マイナス 3 の変更は ▼3 のように見え、プラス 3 は ▲3 のように表示され、テキストと記号は異なる色になります。

DataGridView セルの最初の文字の色を変更するにはどうすればよいですか?

4

2 に答える 2

2

セル内に問題の文字以外のものがある場合、これを行う簡単な方法はありません (なんらかのカスタム ペインティングを行う必要があります)。

これらの文字しかない場合は、CellFormatting イベントを使用すると非常に簡単です。

void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    e.CellStyle.Font = new Font("Arial Unicode MS", 12);
    if (dataGridView1.Columns[e.ColumnIndex].Name == "CorrectColumnName")
    {
        if (e.Value == "▲")
            e.CellStyle.ForeColor = Color.Green;
        else if (e.Value == "▼")
            e.CellStyle.ForeColor = Color.Red;
        else
            e.CellStyle.ForeColor = Color.Black;
    }
}

同じセル内で異なる色が必要な場合は、次のようなコードが必要です (これは CellPainting イベントを処理します)。

void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.ColumnIndex == -1 || e.RowIndex == -1)
        return;

    if (dataGridView1.Columns[e.ColumnIndex].Name == "CorrectColumnName")
    {
        e.Paint(e.CellBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.ContentForeground);

        if (e.FormattedValue.ToString().StartsWith("▲", StringComparison.InvariantCulture))
        {
            RenderCellText(Color.Green, e);
        }
        else if (e.FormattedValue == "▼")
        {
            RenderCellText(Color.Red, e);
        }
        else
            RenderCellText(SystemColors.WindowText, e);

        e.Handled = true;
    }
}

private void RenderCellText(Color color, DataGridViewCellPaintingEventArgs e)
{
    string text = e.FormattedValue.ToString();
    string beginning = text.Substring(0, 1);
    string end = text.Substring(1);
    Point topLeft = new Point(e.CellBounds.X, e.CellBounds.Y + (e.CellBounds.Height / 4));

    TextRenderer.DrawText(e.Graphics, beginning, this.dataGridView1.Font, topLeft, color);
    Size s = TextRenderer.MeasureText(beginning, this.dataGridView1.Font);

    Point p = new Point(topLeft.X + s.Width, topLeft.Y);
    TextRenderer.DrawText(e.Graphics, end, this.dataGridView1.Font, p, SystemColors.WindowText);
}
于 2012-08-06T13:09:01.983 に答える
0

私は一度似たようなことをして、結局これらのキャラクターを彼ら自身のコラムに入れました。

于 2012-08-06T12:34:33.260 に答える