2017-10-10 66 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