如何更改DataGridview中的行颜色

时间:2013-03-19 10:30:42

标签: .net

我有一个添加了表单的控制台应用程序。

此表单中包含数据网格视图,所有属性都保留为默认值。

在Program.cs中,我在Main方法中有这个代码:

CompanyActions objCompanyActions = new CompanyActions();

List<Company> analyzedData = new List<Company>();

List<Company> CompaniesFromExternalSource = objCompanyActions.GetExternalCompanyData(@"company.csv");

analyzedData =  objCompanyActions.Compare(CompaniesFromExternalSource);
AnalysisForm objAnalysisForm = new AnalysisForm();

objAnalysisForm.ShowAnalysisData(analyzedData);
Application.Run(objAnalysisForm);

在表格中我有这段代码:

public void ShowAnalysisData(List<Company> analysisData)
{
     analysisGridView.DataSource = analysisData;

     UpdateGridStyle();

}

  private void UpdateGridStyle()
    {
        foreach (DataGridViewRow row in analysisGridView.Rows)
        {
            string RowType = row.Cells[0].Value.ToString();

            if (RowType == "Insert")
            {
                row.DefaultCellStyle.BackColor = Color.Green;
              //  row.DefaultCellStyle.ForeColor = Color.Black;
            }
            else if (RowType == "Update")
            {
                row.DefaultCellStyle.BackColor = Color.Yellow;
               // row.DefaultCellStyle.ForeColor = Color.Black;
            }
            else
            {
                row.DefaultCellStyle.BackColor = Color.Gray;
              //  row.DefaultCellStyle.ForeColor = Color.Black;
            }
        }

这不起作用。网格仍然保留每行的默认白色背景? 我在这做错了什么?

问候。

1 个答案:

答案 0 :(得分:0)

我认为您正在调用方法在错误的时间更改背景颜色。尝试将它放在CellFormatting中:

private void analysisGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    DataGridViewRow row = analysisGridView.Rows[e.RowIndex];
    string RowType = row.Cells[0].Value.ToString();

    if (RowType == "Insert")
    {
        row.DefaultCellStyle.BackColor = Color.Green;
        //  row.DefaultCellStyle.ForeColor = Color.Black;
    }
    else if (RowType == "Update")
    {
        row.DefaultCellStyle.BackColor = Color.Yellow;
        // row.DefaultCellStyle.ForeColor = Color.Black;
    }
        else
    {
        row.DefaultCellStyle.BackColor = Color.Gray;
        //  row.DefaultCellStyle.ForeColor = Color.Black;
    }
}