Replace "red-cross" in the DataGridViewImageColumn with a "new row" with a custom image

If you specify AllowUserToAddRows in the winforms DataGridView , the user can add new rows manually to the grid. Now I want to add the image button in one column, which should be shown in a new row. But I can’t make him show the image, only the image with the red cross is displayed as if it was not found.

Here's a screenshot of the grid with an annoying image:

enter image description here

The image I want to display is in Properties.Resources.Assign_OneToMany .

I searched everywhere and tried several ways (in the 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 also assigned this image to the DataGridView column collection on the constructor:

enter image description here

So, what is the correct way to specify the default image for a DataGridViewImageColumn that is displayed even if there is no data, but only a new row? If that matters, this is a jpg image: enter image description here

+6
source share
2 answers

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; } } 

enter image description here

I believe that it ignores your assignment of the Image property in the column editor, because this line does not contain anything / Null to begin with.

+5
source

Draw the image manually because the system draws by default:

 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; } } 
+2
source

Source: https://habr.com/ru/post/976058/


All Articles