将编辑文本的颜色更改为红色

时间:2015-03-30 14:23:39

标签: c# winforms colors edit

我有五列的gridview。我已经加载了数据。用户可以编辑列单元格中的文本。如果用户编辑了文本,那些编辑的文本必须为红色。仅编辑

e.g

stackoverflow = StackOverFlow(你会注意到我已经更改/编辑了大写。那些编辑过的大写字母必须改变颜色。在这种情况下,S O和F会将颜色改为红色)

这是我尝试过的但不是那样的方式

 private void Gridview_CellBeginEdit_1(object sender, DataGridViewCellCancelEventArgs e)
    {
        DataGridViewCell cell = Gridview_Output[e.ColumnIndex, e.RowIndex];
        if (cell.Tag != null && cell.Tag.ToString() != cell.Value.ToString())
            cell.Style.ForeColor = Color.Red;
        else
            DataGridViewCell cell = Gridview_Output[e.ColumnIndex, e.RowIndex];
            cell.Tag = cell.Value != null ? cell.Value : "";

    }

1 个答案:

答案 0 :(得分:2)

以下是简单部分的代码示例:

enter image description here

它检查一行(4)中的一列(0),然后绘制在元组列表中准备的字符串。您可以轻松更改数据结构..

List<Tuple<SolidBrush, string>> diffStrings = new List<Tuple<SolidBrush, string>>();

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.RowIndex != 4 || e.ColumnIndex != 0) { return; }  // only one test-cell
    float x = e.CellBounds.Left + 1;
    float y = e.CellBounds.Top + 1;

    e.PaintBackground(e.CellBounds,true);
    foreach (Tuple<SolidBrush, string> kv in diffStrings)
    {
        SizeF size = e.Graphics.MeasureString(kv.Item2, Font, 
                     e.CellBounds.Size, StringFormat.GenericTypographic);
        if (x + size.Width > e.CellBounds.Left + e.CellBounds.Width)  
           {x = e.CellBounds.Left + 1; y += size.Height; }
        e.Graphics.DrawString(kv.Item2, Font, kv.Item1,   x , y);
        x += size.Width;

    }
    e.Handled = true;
}

但是你从哪里获得数据?

以下是我创建测试数据的方法,这些测试数据仅用于以不同颜色显示图形:

SolidBrush c1 = new SolidBrush(Color.Black);
SolidBrush c2 = new SolidBrush(Color.Red);

diffStrings.Add(new Tuple<SolidBrush, string>(c1, "1234"));
diffStrings.Add(new Tuple<SolidBrush, string>(c2, "M"));
diffStrings.Add(new Tuple<SolidBrush, string>(c1, "1234"));
diffStrings.Add(new Tuple<SolidBrush, string>(c2, "ÖÄÜ"));
diffStrings.Add(new Tuple<SolidBrush, string>(c1, "1234"));
diffStrings.Add(new Tuple<SolidBrush, string>(c2, "ÖÄÜ"));
diffStrings.Add(new Tuple<SolidBrush, string>(c1, "1234"));
..

您需要解决编写可以填充结构的Diff函数的问题。如果你知道束缚会有所帮助,比如长度不能改变......

您可以使用Cells&#39; Valuesdiff如果您将这些值存储在Cells&#39; Tags。你必须处理,例如CellBeginEdit和/或CellEndEdit事件来管理两个值的存储,但真正的挑战是获取差异,尤其是在插入或删除字符时!

上面的示例对齐文本TopLeft。包括所有DataGridViewContentAlignment选项会使代码有些复杂化,但仅限于有限的方式。在单词边界之后拆分或管理嵌入的换行符也是如此。 - 编写Diff函数非常困难。请参阅here for an example如何使用现成的..!

相关问题