简体   繁体   English

VB.net-动态创建的列,其中的图像未在datagridview的新行中显示图像

[英]VB.net - Dynamically created column with an Image not displaying image in new row in datagridview

I am building a grid dynamically and want to have a delete image as the last displayed column. 我正在动态构建网格,并希望将删除图像作为最后显示的列。

The image displays fine on the row I add, but the new row doesn't have the image. 我添加的行上的图像显示正常,但是新行没有该图像。 What am I missing? 我想念什么?

When I run the following code I get one row with the image and a second empty row with the 'missing image' icon: 当我运行以下代码时,我将在图像中显示一行,而在第二个空白行中显示“缺少图像”图标:

Public Class Testing
Private dtData As New DataTable

Private Sub Testing_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    LoadMyGrid()
End Sub

Private Sub LoadMyGrid()
    Try


        Dim img As New DataGridViewImageColumn
        Dim inImg As Image = My.Resources.delete
        img.Image = inImg

        dtData.Columns.Add("LanguageId")
        dtData.Columns.Add("Language")
        dtData.Rows.Add(1, "English")

        '--- Load the grid
        With Me.dgv1
            .Columns.Clear()

            .DataSource = dtData
            .Columns(0).Visible = False

            dgv1.Columns.Add(img)
            img.Width = 40
            img.Name = "DELETE"

            .ClearSelection()
        End With
    Catch ex As Exception
        MsgBox("You hit an error")
    End Try
End Sub

End Class

Thanks for any help! 谢谢你的帮助!

  1. Add a variable to store the position of the DELETE column 添加一个变量以存储DELETE列的位置

      Private dgv1DeleteCellIndex as integer = -1 
  2. In the LoadGrid, set the dgv1DeleteCellIndex, locate this before the add of the DELETE column 在LoadGrid中,设置dgv1DeleteCellIndex,在添加DELETE列之前找到它

      dgv1DeleteCellIndex = dgv1.Columns.Count 
  3. After the add of the DELETE column loop through the columns and set the cell value to the image 添加DELETE列后,遍历各列,并将单元格值设置为图像

     For Each row As DataGridViewRow In dgv1.Rows row.Cells(dgv1DeleteCellIndex).Value = My.Resources.delete_16x16 Next 
  4. Update the cell image on RowsAdded event to continue to update the image on any additional new rows added by the user. 在“行添加”事件上更新单元格图像,以继续更新用户添加的任何其他新行上的图像。

     Private Sub dgv1_RowsAdded(sender As Object, e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles dgv1.RowsAdded If dgv1DeleteCellIndex <= 1 Then Exit Sub CType(sender, DataGridView).Rows(e.RowIndex).Cells(dgv1DeleteCellIndex).Value = My.Resources.delete_16x16 End Sub 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM