2014-09-19 24 views
0

我在DatagridView中显示了一些行,它们将第一列设置为ImageandText.when用户选择任何一行,直到具有文本部分的单元格保持图像背景为白色。用于DataGridView中的第一单元显示所述图像和文本在ImageandText中只选择文本Datagridview列

代码:

private void dgvLogDetails_CellPainting(object sender, 
              DataGridViewCellPaintingEventArgs e) 
    { 

     if (e.RowIndex >= 0 && e.ColumnIndex == 0) 
     {     
      e.PaintBackground(e.ClipBounds, true); 
      PointF p = e.CellBounds.Location; 
      e.CellStyle.SelectionBackColor = Color.White; 
      p.X += imgList.ImageSize.Width+8; 


      e.Graphics.DrawImage(imgList.Images[1], e.CellBounds.X+4, 
               e.CellBounds.Y, 16, 16); 
      e.Graphics.DrawString(e.Value.ToString(), 
              e.CellStyle.Font, Brushes.Black, p); 
      e.Handled = true; 
     } 

    } 

上述代码选择,如下面图中所示的完整细胞(图像和文本): enter image description here

我想有像在下面的图片[预计]:

enter image description here

尝试斯利拉姆代码,它是如下显示:

enter image description here

+0

我不知道,但我想'ListView'默认情况下将有你问的功能。如果可行,你可以使用'ListView'。 – 2014-09-19 11:32:41

+0

实际上我所显示的预期图像是使用'ListView'创建的。现在我正在改变它'DataGridView' – 2014-09-19 11:45:41

+0

哦,忽视我的评论然后,看看我的答案是否有帮助。 – 2014-09-19 11:58:15

回答

1

像这样的东西应该做的伎俩。

拨打e.PaintBackground第二个参数设置为false这意味着它不会为您绘制选择背景,那么您可以绘制自己的。

private void dgvLogDetails_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) 
{ 
    if (e.RowIndex >= 0 && e.ColumnIndex == 0) 
    { 
     Bitmap image = imgList.Images[1];//Get the image somewhow 

     bool selected = e.State.HasFlag(DataGridViewElementStates.Selected); 
     e.PaintBackground(e.ClipBounds, false); 

     PointF p = e.CellBounds.Location; 
     p.X += image.Size.Width + 8; 

     if (selected) 
     { 
      RectangleF newRect = new RectangleF(new PointF(e.CellBounds.Left + image.Size.Width, e.CellBounds.Top), new SizeF(e.CellBounds.Width - image.Size.Width, image.Height)); 
      using(SolidBrush brush = new SolidBrush(e.CellStyle.SelectionBackColor)) 
       e.Graphics.FillRectangle(brush, newRect); 
     } 
     e.Graphics.DrawImage(imgList.Images[1], e.CellBounds.X+4, 
              e.CellBounds.Y, 16, 16); 
     e.Graphics.DrawString(e.Value.ToString(), 
             e.CellStyle.Font, Brushes.Black, p); 
     e.Handled = true; 
    } 
} 

下面是它呈现的输出:

enter image description here

+0

非常感谢你Sriram,我已经尝试过,但它仍然没有正确地取消选择图像,我在我编辑的文章中附加了示例图像。 – 2014-09-19 12:04:57

+0

我认为你正在处理其他油漆事件和做其他一些绘画。否则这应该工作,我刚刚测试了一个简单的数据,它按预期工作。交叉检查你的ImageSize是什么等等。如果你不明白,发布一个示例项目,我可以看看,我的意思是我应该能够运行它来查看问题(也包括图像)。我会尽力帮忙。 – 2014-09-19 12:07:53

+0

是的:)在改变if区块的高度和宽度后,它的工作正常,谢谢Sriram。 – 2014-09-19 12:18:09