If you specify AllowUserToAddRows
in a winforms DataGridView
the user can add new rows manually in the grid. Now i want to add an image-button in one column which should be shown also in the new-row. But i cannot get it to show the image, only the red-cross image is shown like as if it wasn't found.
Here's a screenshot of the grid with the annoying image:
The image i want to show is in Properties.Resources.Assign_OneToMany
.
I have searched everywhere and tried several ways like (in constructor):
var assignChargeColumn = (DataGridViewImageColumn)this.GrdChargeArrivalPart.Columns["AssignCharge"];
assignChargeColumn.DefaultCellStyle.NullValue = null;
assignChargeColumn.DefaultCellStyle.NullValue = Properties.Resources.Assign_OneToMany;
or
private void GrdChargeArrivalPart_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
var grid = (DataGridView)sender;
DataGridViewRow row = grid.Rows[e.RowIndex];
if (row.IsNewRow)
{
var imageCell = (DataGridViewImageCell) row.Cells["AssignCharge"];
imageCell.Value = new Bitmap(1, 1); // or ...:
imageCell.Value = Properties.Resources.Assign_OneToMany; // or ...:
imageCell.Value = null;
}
}
Of course i have also assigned this image in the column-collection of the DataGridView
on the designer:
So what is the right way to specify a default image for a DataGridViewImageColumn
which is shown even if there is no data but only the new-row? If that matters, this is the jpg-image:
You can act in the CellFormatting
event:
private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// ToDo: insert your own column index magic number
if (this.dgv.Rows[e.RowIndex].IsNewRow && e.ColumnIndex == 2)
{
e.Value = Properties.Resources.Assign_OneToMany;
}
}
I believe it is ignoring your Image property assignment in the columns editor because that row is Nothing/Null to start with.
Draw the image manually because the system draws the default one:
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == 3 && e.RowIndex >= 0) //change 3 with your collumn index
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
if (dataGridView1 .Rows [e.RowIndex].IsNewRow )
{
Bitmap bmp = Properties.Resources.myImage;
e.Graphics.DrawImage(bmp, e.CellBounds.Left + e.CellBounds.Width / 2 -
bmp.Width / 2, e.CellBounds.Top + e.CellBounds.Height / 2 -
bmp.Height / 2, bmp.Width, bmp.Height);
}
e.Handled = true;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With