根据条件更改datagridview单元格颜色

时间:2013-10-15 11:37:12

标签: c# winforms datagridview

我已经将数据从数据库加载到datagridview并且具有两列目标值和体积,其中体积&gt;目标值,体积单元应该是绿色并且体积<1。目标值然后体积应为红色。我尝试了但是我无法做到。

private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    if (dataGridView1.Rows.Count > 0 && dataGridView1.Columns.Count > 0)
    {
        foreach (DataGridViewRow r in dataGridView1.Rows)
        {
            if (Volume > target value)
            {
                cell.Style.BackColor = Color.AliceBlue;
            } 

12 个答案:

答案 0 :(得分:19)

你需要这样做

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    foreach (DataGridViewRow Myrow in dataGridView1.Rows) 
    {            //Here 2 cell is target value and 1 cell is Volume
        if (Convert.ToInt32(Myrow .Cells[2].Value)<Convert.ToInt32(Myrow .Cells[1].Value))// Or your condition 
        {
            Myrow .DefaultCellStyle.BackColor = Color.Red; 
        }
        else
        {
            Myrow .DefaultCellStyle.BackColor = Color.Green; 
        }
    }
}

同时还要看看Cell Formatting

答案 1 :(得分:19)

我可能会建议 NOT 循环遍历每一行每次调用CellFormating时,因为每次需要刷新一行时都会调用它。

Private Sub dgv_DisplayData_Vertical_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dgv_DisplayData_Vertical.CellFormatting
        Try

            If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "6" Then

                e.CellStyle.BackColor = Color.DimGray
            End If
            If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "5" Then
                e.CellStyle.BackColor = Color.DarkSlateGray
            End If
            If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "4" Then
                e.CellStyle.BackColor = Color.SlateGray
            End If
            If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "3" Then
                e.CellStyle.BackColor = Color.LightGray
            End If
            If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "0" Then
                e.CellStyle.BackColor = Color.White
            End If

        Catch ex As Exception

        End Try

    End Sub

答案 2 :(得分:17)

凯尔和西蒙的答案是对CPU资源的严重浪费。 CellFormattingCellPainting事件发生的次数太多,不应用于应用样式。以下是两种更好的方法:

如果您的DataGridView或至少决定单元格样式的列是只读的,则应更改RowsAdded事件中行的DefaultCellStyle。添加新行时,此事件仅发生一次。应该在那时评估条件,并且应该在其中设置行的DefaultCellStyle。请注意,DataBound情况也会发生此事件。

如果您的DataGridView或这些列允许修改,您应该使用CellEndEditCommitEdit个事件来更改DefaultCellStyle

答案 3 :(得分:3)

foreach (DataGridViewRow row in dgvWebData.Rows)
{
    if (Convert.ToString(row.Cells["IssuerName"].Value) != Convert.ToString(row.Cells["SearchTermUsed"].Value))
    {
        row.DefaultCellStyle.BackColor = Color.Yellow;
    }
    else
    {
        row.DefaultCellStyle.BackColor = Color.White;
    }
}

这对我来说非常有用。即使一行被更改,同样的事件也会照顾。

答案 4 :(得分:1)

让我们说你必须通过了解两件事来为某些细胞(不是该行的所有细胞)着色:

  1. 列的名称或索引。
  2. 将在单元格内部的值。
  3. 在这种情况下,您必须使用事件CellFormatting

    在我的情况下,我像这样使用

    private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
         foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
         {
           if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) > 0)
           {
              row.Cells["Decade1Hours"].Style.BackColor = Color.LightGreen;
           }
           else if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) < 0)
           {
              // row.DefaultCellStyle.BackColor = Color.LightSalmon; // Use it in order to colorize all cells of the row
    
              row.Cells["Decade1Hours"].Style.BackColor = Color.LightSalmon;
           }
         }
    }
    

    结果你可以在这里看到

    enter image description here

    所以在这里你可以按名称访问列中行的某个单元格 row.Cells [&#34; Decade1Hours&#34;]

    你怎么知道这个名字? 在我的情况下,我像这样创建DataGridView列。

    var Decade1Hours = new DataGridViewTextBoxColumn()
    {
       Name = "Decade1Hours",
       Width = 50,
       DataPropertyName = "Decade1Hours",
       ReadOnly = true,
       DefaultCellStyle = new DataGridViewCellStyle()
           {
            Alignment = DataGridViewContentAlignment.MiddleCenter,
            ForeColor = System.Drawing.Color.Black,
            Font = new Font(font, FontStyle.Bold),
            Format = "n2"
          },
       HeaderCell = new DataGridViewColumnHeaderCell()
          {
              Style = new DataGridViewCellStyle()
                   {
                     Alignment = DataGridViewContentAlignment.MiddleCenter,
                     BackColor = System.Drawing.Color.Blue
                   }
           }
    };
    Decade1Hours.HeaderText = "Дек.1";
    dgvTrucksMaster.Columns.Add(Decade1Hours);
    

    嗯......你需要为行中的一些单元格着色,如## 1 4 5和8,你必须使用单元格索引(它从0开始)。

    代码会像

    一样
     private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
      foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
      {
        if (Convert.ToInt32(row.Cells[1].Value) > 0 )
        {
          row.Cells[1].Style.BackColor = Color.LightGreen;
        }
      }
    }
    

答案 5 :(得分:1)

无需循环即可实现,如下所示。

private void dgEvents_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
    {

        FormatRow(dgEvents.Rows[e.RowIndex]);

    }

private void FormatRow(DataGridViewRow myrow)
    {
        try
        {
            if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Error")
            {
                myrow.DefaultCellStyle.BackColor = Color.Red;
            }
            else if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Warning")
            {
                myrow.DefaultCellStyle.BackColor = Color.Yellow;
            }
            else if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Information")
            {
                myrow.DefaultCellStyle.BackColor = Color.LightGreen;
            }
        }
        catch (Exception exception)
        {
            onLogs?.Invoke(exception.Message, EventArgs.Empty);
        }
    }

答案 6 :(得分:1)

<!DOCTYPE html>
<html>
    <head>
        <title>Object reference not set to an instance of an object.</title>
        <meta name="viewport" content="width=device-width" />
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
         }
         @media screen and (max-width: 479px) {
          pre { width: 280px; }
         }
        </style>
    </head>

    <body bgcolor="white">

            <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>

            <h2> <i>Object reference not set to an instance of an object.</i> </h2></span>

            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

            <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

            <br><br>

            <b> Exception Details: </b>System.NullReferenceException: Object reference not set to an instance of an object.<br><br>

            <b>Source Error:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code>

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>

                  </td>
               </tr>
            </table>

            <br>

            <b>Stack Trace:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code><pre>

[NullReferenceException: Object reference not set to an instance of an object.]
   IS_ERSB.Controllers.DebtorsController.GetDebtors(PublicDebtorsPagingViewModel model) in D:\work\dev\is_ersb\IS_ERSB\Controllers\DebtorsController.cs:139
   lambda_method(Closure , ControllerBase , Object[] ) +126
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +241
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +38
   System.Web.Mvc.Async.AsyncControllerActionInvoker.&lt;BeginInvokeSynchronousActionMethod&gt;b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +11
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +138
   System.Web.Mvc.Async.AsyncInvocationWithFilters.&lt;InvokeActionMethodFilterAsynchronouslyRecursive&gt;b__3d() +111
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass46.&lt;InvokeActionMethodFilterAsynchronouslyRecursive&gt;b__3f() +452
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass46.&lt;InvokeActionMethodFilterAsynchronouslyRecursive&gt;b__3f() +452
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass33.&lt;BeginInvokeActionMethodWithFilters&gt;b__32(IAsyncResult asyncResult) +15
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass2b.&lt;BeginInvokeAction&gt;b__1c() +37
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass21.&lt;BeginInvokeAction&gt;b__1e(IAsyncResult asyncResult) +241
   System.Web.Mvc.Controller.&lt;BeginExecuteCore&gt;b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +19
   System.Web.Mvc.MvcHandler.&lt;BeginProcessRequest&gt;b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +51
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +288
</pre></code>

                  </td>
               </tr>
            </table>

            <br>

            <hr width=100% size=1 color=silver>

            <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408

            </font>

    </body>
</html>
<!-- 
[NullReferenceException]: Object reference not set to an instance of an object.
   at IS_ERSB.Controllers.DebtorsController.GetDebtors(PublicDebtorsPagingViewModel model) in D:\work\dev\is_ersb\IS_ERSB\Controllers\DebtorsController.cs:line 139
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.<BeginInvokeAction>b__1c()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
--><!-- 
This error page might contain sensitive information because ASP.NET is configured to show verbose error messages using &lt;customErrors mode="Off"/&gt;. Consider using &lt;customErrors mode="On"/&gt; or &lt;customErrors mode="RemoteOnly"/&gt; in production environments.-->

答案 7 :(得分:0)

惊讶没有人提到一个简单的ImageButton imageButton = (ImageButton)getView().findViewById( R.id.ib); 语句可以确保你的循环每个格式只执行一次(在第一行的第一列)。

v

答案 8 :(得分:0)

我知道这是一篇旧文章,但是我在2018年找到了自己的出路,所以也许其他人也会这样做。我认为,与提供的任何答案相比,OP都有更好的方法(使用dgv_DataBindingComplete事件)。在撰写本文时,所有答案都是使用绘画事件或单元格格式化事件来编写的,这似乎效率很低。

操作是完成操作的99%,他们要做的就是遍历行,测试每行的单元格值,并设置BackColor,ForeColor或要设置的任何其他属性。

请原谅vb.NET语法,但我认为它与C#的距离足够近,因此应该清楚。

Private Sub dgvFinancialResults_DataBindingComplete Handles dgvFinancialResults.DataBindingComplete
            Try
                Logging.TraceIt()
                For Each row As DataGridViewRow in dgvFinancialResults.Rows
                    Dim invoicePricePercentChange = CSng(row.Cells("Invoice Price % Change").Value)
                    Dim netPricePercentChange = CSng(row.Cells("Net Price % Change").Value)
                    Dim tradespendPricePercentChange = CSng(row.Cells("Trade Spend % Change").Value)
                    Dim dnnsiPercentChange = CSng(row.Cells("DNNSI % Change").Value)
                    Dim cogsPercentChange = CSng(row.Cells("COGS % Change").Value)
                    Dim grossProfitPercentChange = CSng(row.Cells("Gross Profit % Change").Value)


                    If invoicePricePercentChange > Single.Epsilon Then
                        row.Cells("Invoice Price % Change").Style.ForeColor = Color.Green
                    Else
                        row.Cells("Invoice Price % Change").Style.ForeColor = Color.Red
                    End If

                    If netPricePercentChange > Single.Epsilon Then
                        row.Cells("Net Price % Change").Style.ForeColor = Color.Green
                    Else
                        row.Cells("Net Price % Change").Style.ForeColor = Color.Red
                    End If

                    If tradespendPricePercentChange > Single.Epsilon Then
                        row.Cells("Trade Spend % Change").Style.ForeColor = Color.Green
                    Else
                        row.Cells("Trade Spend % Change").Style.ForeColor = Color.Red
                    End If

                    If dnnsiPercentChange > Single.Epsilon Then
                        row.Cells("DNNSI % Change").Style.ForeColor = Color.Green
                    Else
                        row.Cells("DNNSI % Change").Style.ForeColor = Color.Red
                    End If

                    If cogsPercentChange > Single.Epsilon Then
                        row.Cells("COGS % Change").Style.ForeColor = Color.Green
                    Else
                        row.Cells("COGS % Change").Style.ForeColor = Color.Red
                    End If

                    If grossProfitPercentChange > Single.Epsilon Then
                        row.Cells("Gross Profit % Change").Style.ForeColor = Color.Green
                    Else
                        row.Cells("Gross Profit % Change").Style.ForeColor = Color.Red
                    End If
                Next
            Catch ex As Exception
                Logging.ErrorHandler(ex)
            End Try
        End Sub

答案 9 :(得分:0)

private void dataMain_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (dataMain.Columns[e.ColumnIndex].Name == "colStatus")
        {
            if (int.Parse(e.Value.ToString()) == 2)
            {
                dataMain.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.OrangeRed;
                dataMain.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.White;

            }
        }
    }

答案 10 :(得分:-1)

//After Done Binding DataGridView Data
foreach(DataGridViewRow DGVR in DGV_DETAILED_DEF.Rows)
{
    if(DGVR.Index != -1)
    {
        if(DGVR.Cells[0].Value.ToString() == "البدلات")
        {
            CurrRType = "البدلات";
            DataGridViewCellStyle CS = DGVR.DefaultCellStyle;
            CS.BackColor = Color.FromArgb(0,175,100);
            CS.ForeColor = Color.FromArgb(0,32,15);

            CS.Font = new Font("Times New Roman",12,FontStyle.Bold);
            CS.SelectionBackColor = Color.FromArgb(0,175,100);
            CS.SelectionForeColor = Color.FromArgb(0,32,15);
            DataGridViewCellStyle LCS = DGVR.Cells[DGVR.Cells.Count - 1].Style;
            LCS.BackColor = Color.FromArgb(50,50,50);
            LCS.SelectionBackColor = Color.FromArgb(50,50,50);
        }
        else if(DGVR.Cells[0].Value.ToString() == "الإستقطاعات")
        {
            CurrRType = "الإستقطاعات";
            DataGridViewCellStyle CS = DGVR.DefaultCellStyle;
            CS.BackColor = Color.FromArgb(175,0,50);
            CS.ForeColor = Color.FromArgb(32,0,0);
            CS.Font = new Font("Times New Roman",12,FontStyle.Bold);
            CS.SelectionBackColor = Color.FromArgb(175,0,50);
            CS.SelectionForeColor = Color.FromArgb(32,0,0);
            DataGridViewCellStyle LCS = DGVR.Cells[DGVR.Cells.Count - 1].Style;
            LCS.BackColor = Color.FromArgb(50,50,50);
            LCS.SelectionBackColor = Color.FromArgb(50,50,50);
        }
    }
}

答案 11 :(得分:-1)

简单明了

private void dataGridView1_cellformatting(object sender,DataGridViewCellFormattingEventArgs e)
{
     var amount = (int)e.Value;

     // return if rowCount = 0
     if (this.dataGridView1.Rows.Count == 0)
         return;

     if (amount > 0)
         e.CellStyle.BackColor = Color.Green; 
     else
         e.CellStyle.BackColor = Color.Red;

}

看看cell formatting