Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在DataGridView的同一列和同一单元格中以2种颜色显示文本_C#_.net_Winforms_Datagridview - Fatal编程技术网

C# 在DataGridView的同一列和同一单元格中以2种颜色显示文本

C# 在DataGridView的同一列和同一单元格中以2种颜色显示文本,c#,.net,winforms,datagridview,C#,.net,Winforms,Datagridview,我想在Windows应用程序Winform.NET的DataGridView中,基于同一列和同一单元格,以两种颜色显示文本。如下图所示。可能吗 您可以将自定义列与富文本框一起使用。看看 从 添加CellPaint事件处理方法完美地解决了这个问题 void datagridview_CellPainting(object sender,DataGridViewCellPaintingEventArgs e) { if(datagridview.Columns[e.ColumnsIndex].N

我想在Windows应用程序Winform.NET的DataGridView中,基于同一列和同一单元格,以两种颜色显示文本。如下图所示。可能吗


您可以将自定义列与富文本框一起使用。看看

添加CellPaint事件处理方法完美地解决了这个问题

void datagridview_CellPainting(object sender,DataGridViewCellPaintingEventArgs e)
{
  if(datagridview.Columns[e.ColumnsIndex].Name=="content")
  {
      string content="this is a test message,to illustrate this words fine";
      string []line=content.Split(',');
      StringFormat sf=new StringFormat();
      sf.Alignment=StringAlignment.Center;
      sf.LineAlignment=StringAlignment.Center; 

      e.Paint(e.CellBounds, DataGridViewPaintParts.All&~DataGridViewPaintParts.ContentForeground);

      SizeF []size=new SizeF[line.Length];
      for(int i=0;i<line.Length;++i)
      {
          size[i]=e.Graphics.MeasureString(line[i],e.CellStyle.Font);
      }

      RectangleF rec=new RectangleF(e.CellBounds.Location,new Size(0,0));
      using(SolidBrush bblack=new SolidBrush(Color.Black),bred=new 
                                                    SolidBrush(Color.Red))
      {
           for(int i=0;i<line.Length;++i)
           {
               rec=new RectangleF(new 
                       PointF(rec.Location.X+rec.Width,rec.Location.Y),new 
                              SizeF(size[i].Width,e.CellBounds.Height));
               if(i%2==0)
               {                  
                    e.Graphics.DrawString(line[i], e.CellStyle.Font, bred, rec, sf);
               }
               else
               {
                    e.Graphics.DrawString(line[i].e.CellStyle.Font, bblack, rec, sf);
               }
           }
      }
      e.Handled=true;
  }
}
上面的代码使这是一条测试消息,用于说明此单词在列内容的单元格内精细显示,如下所示
这是一条红色的测试消息,用黑色来说明这个单词。

这不是答案。@t如果你点击链接,你会得到完整的详细信息。这里不欢迎只链接答案。链接一直都会失效..您需要拥有绘制DGV ie代码的CellPaint事件。这里有很多例子……可能,但可能有些过头了。