In this post, I am going to explain how to use images as
buttons for DataGridView. We will work on the DataGridView used in part1 for this purpose.
1.
Include one Image column Delete in DataGridView as follows.
2.
Open DataGridView
Tasks>Edit Columns.
3.
Click Delete
in the Selected Column section.
4.
Select Image
in Unbound Column Properties section
to specify path of image for the Delete
column.
You can either specify the image path from the resources
file or import the image from a
local resource.
local resource.
5.
Notice that Image
property is now set to the selected path.
6.
Click OK
to save the changes.
7.
Run the solution.
Notice that the Delete
column appears as an image column. However, if you mouse over the Delete column, it appears like a normal
column.
To make the Delete column look like a button when mouse moves over the cells of
the image column, define a CellMouseMove
event and set the cursor to Hand
cursor.
8.
In the DataGridView
properties, define CellMouseMove and
CellMouseClick events for the DataGridView
with the name dgvDashboard.
9.
Add the following code to the Dashboard.cs file.
private void dgvDashboard_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
{
//Skip the Column and Row headers
if (e.ColumnIndex < 0 ||
e.RowIndex < 0)
{
return;
}
//Check the condition as per the requirement casting the
cell value to the appropriate type
// here 4
represents delete column index in grid starting from 0th column
if (e.ColumnIndex == 4)
dgvDashboard.Cursor = Cursors.Hand;
else
dgvDashboard.Cursor
= Cursors.Default;
}
Notice that when you mouse over the cells of the Delete column, the cursor changes to the
hand cursor.
Also notice that when you mouse over the cells of the
other columns, the cursor will be a default one.
Now the Delete
column looks like an image button column, but we still have to define Click event for the cells in the Delete column.
To define Click
event for the cells in the Delete
column, add CellMouseClick event for DataGridView and add the following code in Dashboard.cs file.
private void dgvDashboard_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
//Skip
the Column and Row headers
if (e.ColumnIndex < 0 || e.RowIndex < 0)
{
return;
}
if (e.ColumnIndex == 4)
{
dgvDashboard.Rows.RemoveAt(e.RowIndex);
}
}
After you delete the second row, the new grid appears
as seen in the following figure.
Conclusion
In this post, we have seen how to add image columns and
define click events for them. We also learnt about events like CellMouseClick and CellMouseMove.
In the next post, I will explain how to dynamically change
images based on the status or column of a grid. Stay tuned J
No comments:
Post a Comment