【问题标题】:vb.net color first char in cellvb.net颜色单元格中的第一个字符
【发布时间】:2012-08-06 12:27:02
【问题描述】:

在 VB .NET 中,我根据某些计算将 3 个字符添加到 DataGridView 单元格中。

它们是等级变化箭头,工作正常,但我希望向上箭头为绿色,向下箭头为红色。

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

因此,在单元格中,负 3 的变化看起来像 ▼3,加 3 看起来像 ▲3,其中文本和符号是不同的颜色。

如何更改 DataGridView 单元格中第一个字符的颜色?

【问题讨论】:

  • 我们是在谈论 WPF 还是 WinForms?
  • 我认为不可能只使那个字符变成红色或绿色我认为你必须设置单元格的 .forecolor
  • 好像死路一条……
  • 您可以随时尝试绘制事件并自己绘制字符
  • 我应该放弃或改变整个单元格的颜色

标签: vb.net datagridview colors char


【解决方案1】:

如果您在单元格中除了有问题的角色之外还有其他任何内容(您需要进行某种形式的自定义绘画),则没有简单的方法来做到这一点。

如果您只有这些字符,那么使用 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);
}

【讨论】:

  • 我现在要制作一个自定义绘画代码的原型——如果您自己不能将其翻译成 VB.Net,我可以提供该代码。这不是我的第一语言,所以我给出了可以从内存中编码的 c#。
  • 但是排名数字会保持黑色吗?
  • @user1570048 你是什么意思排名数?与向上和向下箭头相同的单元格中是否有文本?然后你将需要像我的第二个选项这样的东西(同样,如果你真的需要它,我可以通过一个 VB.Net 示例来工作)
  • c# 很好会转换成 vb 告诉你发生了什么
【解决方案2】:

我曾经做过类似的事情,最后把这些字符放在自己的列中。

【讨论】:

    猜你喜欢
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    • 1970-01-01
    相关资源
    最近更新 更多