F Rez F Rez - 4 months ago 24
Vb.net Question

Null Value DataGridView

good morning everyone

I`m having a little issue with a dgv. Im trying to fill it with the result of a function that shows the name of the files in a folder and the amount of lines each file has.

But for some reason im having a null vaule on the datagrid and i dont know how to remove it. I`ve been doing this without much knowledge of vb.net or coding whatsoever so any help would be greatly apreciated

Here is the code:

Imports System
Imports System.Linq
Imports System.Collections
Imports System.IO
Imports System.IO.StreamReader
Imports System.IO.DirectoryInfo

Public Class MainForm

'asigna la var como datatable
Dim results1 As New DataTable

Private Sub Boton_Buscar_Click(sender As System.Object, e As System.EventArgs) Handles Boton_Buscar.Click

'muestra el dialogo y guarda el dir
FBD1.ShowDialog()
TextBox1.Text = FBD1.SelectedPath
FSW1.Path = TextBox1.Text

'indica el datasource al datagrid
Try
DGV1.DataSource = GetLineCount()

Catch ex As Exception
MsgBox(ex.Message)
End Try

End Sub

'devuelve archivos y su num de lineas
Public Function GetLineCount() As DataTable

results1.Columns.Add(0)
results1.Columns.Add(1)


'array para los tipos de archivo
Dim MyFileArray As [String]() = New [String](7) {"*.txt", "*.doc", "*.docx", "*.odt", "*.pdf", "*.rtf", _
"*.csv", "*.vb"}

'array para los directorios
Dim MyDirectoryArray As [String]() = New [String](0) {TextBox1.Text}

' loop directorios
For Each sd As [String] In MyDirectoryArray
Dim dir As New DirectoryInfo(sd)

'loop los tipos de archivos
For Each sFileType As [String] In MyFileArray

'loop los archivos ante el contador
For Each file__1 As FileInfo In dir.GetFiles(sFileType)

Dim LineCount = System.IO.File.ReadAllLines(file__1.FullName).Count()

'alimenta el datagrid con los datos nuevos
results1.Rows.Add()
results1.Rows.Add.Item(0) = "FileName: " & file__1.FullName
results1.Rows.Add.Item(1) = "LineCount: " & LineCount

Next

Next

Next

Return results1

End Function

End Class


And here is the output im getting:

Any help is very welcome, have a good day

Answer

The reason you are getting null values is that you're trying to add the row by one cell at a time.

Instead of

results1.Rows.Add()
results1.Rows.Add.Item(0) = "FileName: " & file__1.FullName
results1.Rows.Add.Item(1) = "LineCount: " & LineCount

Try

results1.Rows.Add("FileName: " & file__1.FullName, "LineCount: " & LineCount)

Your current code adds three rows instead of 1 each time: first an empty row, then a row with cell(0) filled and then null, and then a row with null and then cell(1) filled.

Comments