【问题标题】:how to change color text when edited in datagridview在datagridview中编辑时如何更改颜色文本
【发布时间】:2015-02-27 14:46:50
【问题描述】:

如何更改正在编辑的文本的颜色。我有一个里面有值的datagridview。我想要的是当用户编辑单元格内的文本时。它必须将文本更改为红色我该怎么做?

    private void Gridview_Output_CellFormatting_1(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (Gridview_Output.Columns[e.ColumnIndex].Name == "FontOut")
        {
            Gridview_Output.Rows[e.RowIndex].Cells[3].Value = "FontOut";
            DataGridViewCellStyle Cstyle = new DataGridViewCellStyle();
            Cstyle.ForeColor = Color.Red;
        }
    }

【问题讨论】:

  • 您的问题解决了吗?
  • 没有搜索它只改变编辑文本的颜色

标签: c# winforms datagridview colors


【解决方案1】:

这适用于所有列:

private void Gridview_Output_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewCell cell = Gridview_Output[e.ColumnIndex, e.RowIndex];
    cell.Style.ForeColor = Color.Red;
}

如果你想限制它,只需添加如下检查:

if (cell.OwningColumn.Name == "yourColumnName")
    cell.Style.ForeColor = Color.Red

如果您想在用户编辑单元格时保持颜色但保留与之前相同的值,请使用这两个事件(如果您的 Tag 未使用):

private void DGV_Points_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
    DataGridViewCell cell = DGV_Points[e.ColumnIndex, e.RowIndex];
    cell.Tag = cell.Value != null ? cell.Value : "";
}

private void DGV_Points_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewCell cell = DGV_Points[e.ColumnIndex, e.RowIndex];
    if (cell.Tag != null && cell.Tag.ToString() != cell.Value.ToString()) 
        cell.Style.ForeColor = Color.Red;
}

【讨论】:

  • 如果用户编辑文本,我希望它改变颜色。没有用红色打字。
  • 好的,没问题,只需省略 CellBeginEdit 事件并在 CellEndEdit 中设置 ForeColor = Color.Red.. 你验证单元格吗?
  • 文本是黑色的,但经过编辑后,我希望它是红色的
  • 我希望它保持黑色,仅在您编辑后将颜色变为红色
  • 正是上面的代码所做的。你有没有,也许,没有删除原来的CellBeginEdit 事件?
【解决方案2】:

所以你想用红色显示编辑的值吗??

那就这样吧..

    object previousValue;

    public Form1()
    {
        dgv.CellBeginEdit += dgv_CellBeginEdit;
        dgv.CellEndEdit += dgv_CellEndEdit;
    }

    void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        if (dgv[e.ColumnIndex, e.RowIndex].Value != previousValue) 
              dgv[e.ColumnIndex, e.RowIndex].Style.ForeColor = Color.Red;
    }

    void dgv_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
    {
        previousValue = dgv[e.ColumnIndex, e.RowIndex].Value;
    }

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    相关资源
    最近更新 更多