1

我目前正在这样做:

    private void dgResults_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        // Would be nice if we could do this on databind of each row instead and avoid looping
        for (int r = 0; r < dgResults.Rows.Count; r++)
        {
            if (dgResults.Rows[r].Cells[5].Value.ToString() == "0")
            {
                for (int c = 0; c < dgResults.Rows[r].Cells.Count; c++)
                {
                    dgResults.Rows[r].Cells[c].Style.ForeColor = Color.White;
                }
            }
        }
    }

但由于某种原因,它总是错过第一行。有一个更好的方法吗?

4

4 回答 4

1

您不需要内部循环来为一行中的每个单元格设置样式,而是可以使用DefaultCellStyle.ForeColor将为整行设置样式的属性。

试试这个代码

private void dgResults_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        // Would be nice if we could do this on databind of each row instead and avoid looping
        for (DataGridViewRow row in dgResults.Rows)
        {
            if (row.Cells[5].Value.ToString() == "0")
            {
               row.DefaultCellStyle.ForeColor = Color.White;                
            }
        }
    }
于 2013-11-05T06:24:47.127 回答
1

由于某种原因,它总是错过第一行

我不知道为什么(您的代码似乎正确)。如果要避免循环,可以使用CellFormatting事件。

private void dgResults_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
    if (dgResults.Rows[e.RowIndex].Cells[5].Value.ToString() == "0")
    {
        dgResults.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.White;
    }
}
于 2013-11-04T22:44:49.417 回答
0

这是因为选择了第一行。

    public TransparentDataGridView()
    {
        this.SelectionChanged += TransparentDataGridView_SelectionChanged;
    }

    void TransparentDataGridView_SelectionChanged(object sender, EventArgs e)
    {
        ClearSelection();
    }

修复它。

于 2013-11-04T23:24:07.203 回答
0

编辑:

try
{
    foreach (DataGridViewRow dgvc in dgResults.Rows.Cast<DataGridViewRow>().Where(g => g.Cells[5].Value.ToString() == "0"))
    {
        dgvc.DefaultCellStyle.ForeColor = Color.White;
    }
}
catch (Exception)
{

}
于 2013-11-05T00:26:06.613 回答