我想知道是否以及如何在 datagridview 的边缘添加一个小图像,如图中圈出的那样。即:每一行都应该在边距中有图像。
注意:我不想在 datagridview 中添加新的图像列。
试试这个代码,不完整但对你有好处,这会为所有单元格添加相同的图像,点击图像会显示一些消息(你可以自定义):
//CellPainting event handler to draw image on cell
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex > -1 && e.RowIndex > -1 && e.Value != null)
{
e.Handled = true;
e.PaintBackground(e.CellBounds, true);
e.Graphics.DrawImage(Properties.Resources.YourIMAGE, new Rectangle(e.CellBounds.Left, e.CellBounds.Top + 2, e.CellBounds.Height - 4, e.CellBounds.Height - 4));
StringFormat sf = new StringFormat() { LineAlignment = StringAlignment.Center };
e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, new SolidBrush(e.CellStyle.ForeColor), new Rectangle(e.CellBounds.Left + e.CellBounds.Height, e.CellBounds.Top, e.CellBounds.Width - e.CellBounds.Height, e.CellBounds.Height), sf);
}
}
bool imageClicked;
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
CheckIfClickOnImage(e);
}
private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
CheckIfClickOnImage(e);
}
private void CheckIfClickOnImage(DataGridViewCellMouseEventArgs e){
Rectangle rect = dataGridView1[e.ColumnIndex, e.RowIndex].ContentBounds;
rect.Offset(-rect.Width + rect.Height + 4, 2);
rect.Location.Offset(0, 2);
if (rect.Contains(e.Location))
{
imageClicked = true;
MessageBox.Show(string.Format("You clicked on the image of the cell({0},{1})", e.ColumnIndex, e.RowIndex));
}
}
//Clicking on a cell sometimes makes the clicked cell be in edit mode. So we can avoid this using some kind of flag
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if (imageClicked)
{
e.Cancel = true;
imageClicked = false;
}
}
您的要求比我之前发布的代码还要简单,这里是您需要的代码:
private void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == -1 && e.RowIndex > -1)
{
e.Handled = true;
e.PaintBackground(e.CellBounds, true);
e.Graphics.DrawImage(Properties.Resources.yourIMAGE, new Rectangle(e.CellBounds.Left + 5, e.CellBounds.Top + 5, e.CellBounds.Width - 10, e.CellBounds.Height - 10));
}
}
//To handle the click on a Row header, you can add custom code to a RowHeaderMouseClick event handler
private void dataGridView_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
MessageBox.Show(e.RowIndex.ToString());
}