簡體   English   中英

用自定義圖像替換“new-row”的DataGridViewImageColumn中的“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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM