如果文件没有退出则返回no error vb

时间:2017-07-05 21:37:55

标签: vb.net datagridview

我已经启动了这个应用程序,它的工作正常,但我有一个小错误,但我找不到解决错误的解决方案。

我已调试它并且错误因为文件不存在 有没有办法让我用所有* .gif图像填充我的datagridview从一个目录,并检查它是否为null或类似的东西。 我的意思是,有什么方法可以填充所选目录中的所有gif图像? 事实上,我已准备好尝试这样但我收到一个错误"提供的列已经属于DataGridView控件。

Well finaly i have found a solution to load all images from a directory to a datagridview programmatic

这是工作代码

Public Class Form5

Private Sub addBtn_Click(sender As Object, e As EventArgs) Handles addBtn.Click
    'Populate()
    ShowImages()

End Sub
'CLEAR DATAGRIDVIEW
Private Sub clearBtn_Click(sender As Object, e As EventArgs) Handles clearBtn.Click
    DataGridView1.Rows.Clear()
End Sub
'WHEN AN IMAGE IS CLICKED
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    MessageBox.Show("You Clicked Image At Col: " + e.ColumnIndex.ToString() + " Row: " + e.RowIndex.ToString())
End Sub

Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Public Sub ShowImages()

    Dim directory As New System.IO.DirectoryInfo("C:\avitogifconverter\")

    If directory.Exists Then

        Dim pngFiles() As System.IO.FileInfo = directory.GetFiles("*.gif")

        For Each pngFile As System.IO.FileInfo In pngFiles

            If pngFile.Exists Then

                Dim image = System.Drawing.Image.FromFile(pngFile.FullName)

                Using image
                    Dim count = 1
                    ' do something with the image like show in picture box
                    'CONSTRUCT IMG COLUMN
                    Dim imgCol As DataGridViewImageColumn = New DataGridViewImageColumn()
                    imgCol.HeaderText = "Photo"
                    imgCol.Name = "Col 1"
                    DataGridView1.Columns.Add(imgCol)
                    'CONSTRUCT ROWS
                    'FIRST ROW

                    Dim img As Image = System.Drawing.Image.FromFile(pngFile.FullName)

                    Dim row As Object() = New Object() {img, img, img}


                    DataGridView1.Rows.Add(row)
                End Using

            End If
        Next
    End If
End Sub
End Class

1 个答案:

答案 0 :(得分:0)

使用Directory.EnumerateFiles,您可以执行以下操作:

Dim row = New List(Of Image)(3)
For Each filename In Directory.EnumerateFiles("C:\avitogifconverter", "*.gif")
    row.Add(Image.FromFile(filename))
    If row.Count = 3 Then
        DataGridView1.Rows.Add(row.ToArray())
        row.Clear()
    End If
Next
If row.Count > 0 Then
    DataGridView1.Rows.Add(row.ToArray())
    row.Clear()
End If