2017-10-10 36 views
0

我想要DataGridViewButtonColumn充當DataGridViewCheckBoxColumn。意思是在按鈕內部有一些圖像作爲true,另一圖像爲false,並通過DataMember綁定到屬性。 我認爲一個類繼承DataGridViewCheckBoxColumnoverridepaint方法「應該」的工作。DataGridViewButtonColumn充當DataGridViewCheckBoxColumn

+0

那麼什麼是你的問題?你有什麼嘗試? –

+0

到目前爲止我卡在塗料的方法。不知道該怎麼辦 – ihisham

+0

不需要繼承任何東西。只需使用網格的CellPainting事件。 – LarsTech

回答

1

只要使用DataGridViewCheckBoxColumn,但處理CellPaint事件DataGridView並繪製一個圖像檢查狀態和另一個未選中狀態。

創建一個名爲FormForm1再滴上形成DataGridView控制,並用下面的代碼替換的Form1.cs內容。還請確保您將Checkedenter image description hereUnCheckedenter image description here圖像添加到Resources

然後你會看到這樣的結果:

enter image description here

public Form1() 
{ 
    InitializeComponent(); 
    this.Load += Form1_Load; 
    this.dataGridView1.CellPainting += dataGridView1_CellPainting; 
} 
private void Form1_Load(object sender, EventArgs e) 
{ 
    var dt = new DataTable(); 
    dt.Columns.Add("Column1", typeof(bool)); 
    dt.Rows.Add(false); 
    dt.Rows.Add(true); 
    this.dataGridView1.DataSource = dt; 
} 
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) 
{ 
    if (e.ColumnIndex == 0 && e.RowIndex >= 0) 
    { 
     var value = (bool?)e.FormattedValue; 
     e.Paint(e.CellBounds, DataGridViewPaintParts.All & 
           ~DataGridViewPaintParts.ContentForeground); 
     var img = value.HasValue && value.Value ? 
      Properties.Resources.Checked : Properties.Resources.UnChecked; 
     var size = img.Size; 
     var location = new Point((e.CellBounds.Width - size.Width)/2, 
            (e.CellBounds.Height - size.Height)/2); 
     location.Offset(e.CellBounds.Location); 
     e.Graphics.DrawImage(img, location); 
     e.Handled = true; 
    } 
} 
+0

快速問題我將代碼移到了獨立的DataGridViewColumn中,所以我可以自由使用它。它的工作,但我沒有得到視覺更新,當我在編輯模式下,只有當我退出更新纔會生效。任何想法爲什麼? – ihisham

+0

你確定你是從'DataGridViewCheckBoxColumn'派生的嗎?嗯,也許最好發佈一個包含您創建的自定義列的代碼的新問題。 –

+0

在這裏我發佈的代碼使用的問題https://stackoverflow.com/questions/46709110/custom-datagridviewcheckboxcell-visual-update-doesnt-work-in-edit-mode – ihisham