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!
Add a variable to store the position of the DELETE column
Private dgv1DeleteCellIndex as integer = -1
In the LoadGrid, set the dgv1DeleteCellIndex, locate this before the add of the DELETE column
dgv1DeleteCellIndex = dgv1.Columns.Count
After the add of the DELETE column loop through the columns and set the cell value to the image
For Each row As DataGridViewRow In dgv1.Rows row.Cells(dgv1DeleteCellIndex).Value = My.Resources.delete_16x16 Next
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.