![](/img/trans.png)
[英]Datagridview : DataGridViewImageColumn displays a red cross
[英]Replace “red-cross” in DataGridViewImageColumn of “new-row” with custom image
如果在winforms DataGridView
指定AllowUserToAddRows
,则用户可以在网格中手动添加新行。 现在我想在一列中添加一个图像按钮,它也应该在新行中显示。 但我不能让它显示图像,只有红十字图像显示就像没有找到。
这是带有令人讨厌的图像的网格的屏幕截图:
我想要显示的图像位于Properties.Resources.Assign_OneToMany
。
我到处搜索并尝试了几种方式(在构造函数中):
var assignChargeColumn = (DataGridViewImageColumn)this.GrdChargeArrivalPart.Columns["AssignCharge"];
assignChargeColumn.DefaultCellStyle.NullValue = null;
assignChargeColumn.DefaultCellStyle.NullValue = Properties.Resources.Assign_OneToMany;
要么
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;
}
}
当然我还在设计器的DataGridView
的列集合中分配了这个图像:
那么为DataGridViewImageColumn
指定默认图像的正确方法是什么,即使没有数据也只显示新行? 如果这很重要,这是jpg图像:
您可以在CellFormatting
事件中执行操作:
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;
}
}
我相信它忽略了列编辑器中的Image属性赋值,因为该行的开头是Nothing / Null。
手动绘制图像,因为系统绘制默认图像:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.