2014-09-19 28 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