将图像图标添加到Winform datagridview边距

时间:2013-06-19 06:58:41

标签: c# .net winforms

我想知道是否以及如何在datagridview的边缘添加一个小图像,如图中圈出的所示。即:每行应该在边缘有图像。

注意:我不想在datagridview中添加新的图像列。

enter image description here

1 个答案:

答案 0 :(得分:1)

试试这段代码,不完整,但对你开始有好处,这会将相同的图片添加到所有单元格,点击图片会显示一些消息(你可以自定义):

    //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());
}