Exception while loading file to listbox. Value cannot be null? - vb.net

I got a big problem. I try to load data to listbox from a file, but when I load it I got an exception at last line of file. It says "Value cannot be null. Parameter name: item".
I use this code
ListBox2.Items.Clear() 'clear listbox2
For i As Integer = 0 To ListBox1.Items.Count - 1
Dim read_text As New StreamReader(ListBox1.Items.Item(i).ToString, System.Text.Encoding.GetEncoding(1250)) ' listbox1.items.item(i) is the path of file I load data from
Try
Do While read_text.Peek >= 0
If read_text.ReadLine.ToString.Contains(":") Then 'dont load lines without ":" mark
ListBox2.Items.Add(read_text.ReadLine)
End If
Loop
read_text.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next i
Where is the problem? Can anybody help? ;)

The exception is thrown by ListBox.Items.Add see the MSDN documentation. You aren't allowed to add null (or nothing in VisualBasic) to the ListBox.Items
Also as written in the comment, you read one line and check it with contains, but read the next one to add it to the list.
You should change the code so that you save the line you get from ReadLine in a variable. Than check if it's not nothing and if it contains ":" - in that case you can add the variable to the ListBox2.Items.

Related

Reading a particular line of a text file in an array in VB.NET

I am trying to read specific lines from a text file in an array (e.g. line 16,25,34, and so on). Could you please let me know if it is possible and how that could be done?
Thanks in advance,
Pouya
Yes it is possible. Since this is not a code based will elaborate how to achieve that. This will depends on the size of your target file. If the size in not to large for your PC's memory then you can read the whole textfile while reading keep the count.
Then start when the file has been read to end to go through your lines using regex.
Check:
VB.NET Read Certain text in a text file
your solution is here:
http://www.dreamincode.net/forums/topic/56497-go-to-a-particular-line-in-a-text-file-using-vbnet/
How to read a specific line from a text file in VB
Ok, here's I've also quoted the code to help you from the second last like I provided above. I'm sure you know how to get data from an Array so instead of line you will add your array.
Public Function
ReadSpecifiedLine(ByVal line As
Integer) As String
'create a variable to
hold the contents of the file
Dim contents As String = String.Empty
'create a variable to
hold our line contents
Dim lineText As String =
String.Empty
' always use a
try...catch to deal
' with any exceptions
that may occur
Try
'Using lineByLine As New IO.StreamReader(_fileName)
Dim lineCount As Integer = 0
While Not lineByLine.EndOfStream
lineByLine.ReadLine ()
If lineCount = line Then
' you can replace the line variable above or use the And Or to match the lines from your array.
lineText = lineByLine.ReadLine()
End If
lineCount += 1
End While
End Using
Catch ex As FileNotFoundException
lineText = String.Empty
_returnMessage = ex.Message
Catch ex As Exception
' deal with any errors
_returnMessage = ex.Message
End Try
Return lineText
End Function
Hope this helps you.(Sorry having some problems in code formatting it some part maybe not formeted, or visible. If End Function is not visible please refer to the link. I've tried so many times to formet this but it not properly formeted, I'm using a Mobile phone.)

Get files from sub directory using vb.net

I have a directorry which contains many folders such as folder1,folder2,folder3 etc..which contains sub-directories..In that I have a folder name "special" which contains some files
Now I would like to get all those files based on the name of the sub-directory
Example:
C:\Users\desktop\Myfolder\folder1\special\
C:\Users\desktop\Myfolder\folder2\special\
C:\Users\desktop\Myfolder\folder3\special\
C:\Users\desktop\Myfolder\folder4\special\
Now I need to get all the files from each special folder of all the folder1,folder2,folder3 and folder4 and display them in gridview.
grid1.DataSource = (From p1 In IO.Directory.GetFiles("C:\Users\desktop\Myfolder\", "*", IO.SearchOption.AllDirectories)
Where p1.Contains("\special\"))
grid1.DataBind()
I just worked on your case, and i think the following piece of code will suits your requirement. The given code will drill through the directories and it display the filenames if it is comes under the special directory. Comment me back if i wrongly answered your question.
The procedure,
Private Sub GetFiles(ByVal xPath As String)
Try
If Directory.GetDirectories(xPath).Length > 0 Then
For Each xDir As String In Directory.GetDirectories(xPath)
If Directory.Exists(xDir) Then
GetFiles(xDir)
End If
Next
End If
If Directory.GetFiles(xPath).Length > 0 Then
For Each xDir As String In Directory.GetFiles(xPath)
If UCase(Path.GetDirectoryName(xDir)).EndsWith("SPECIAL") Then
MsgBox(Path.GetFileName(xDir))
End If
Next
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
and the call,
call GetFiles("D:\test")
if your datagridview is datagridview1 and countains two columns and you want to add the name file and last modified here is the solution ..
For Each sDir In Directory.GetDirectories("C:\Users\desktop\Myfolder\", "special", SearchOption.AllDirectories)
For Each File In Directory.GetFiles(sDir)
Dim detailedfile As New IO.FileInfo(File)
DataGridView1.Rows.Add(detailedfile.Name, detailedfile.LastAccessTime)
Next
next
if you want to add more details in the gridview you have just to add more columns and more integers in the DataGridView1.Rows.Add

Is it possible to customize error message "Column does not allow nulls" in a datatable?

I have a form with controls bound to a datatable in VB.net.
When keeping empty a field that should be filled, I'm receiving the error message : Column does not allow nulls.
Is it possible to replace this error message string by another one ?
There are a lot of ways when it comes to error handling.
You could get your code to throw a custom error alert:
This will throw an alert with the text: NullCollumContent
Try
'your code here
Catch ex As Exception
Throw New System.Exception("NullCollomContent")
End Try
Also as K3rnel31 explained:
This will just show a simple message box to the user
Try
'your code here
Catch ex As Exception
msgbox("error message here")
End Try
You could also use If statements to check the string:
This if checks the length of the string and checks if its equal to 0:
If Not yourString.Length = 0 Then
'your code here
else
'some error handling here
End If
This if checks if your string is equal to "" which basically means an empty string:
If Not yourString Is "" Then
'your code here
Else
'some error handling here
End If
Try
'your code here to the datatable
Catch ex As Exception
msgbox("changed error string here")
End Try
Thank you all for your answers but that's not really my problem.
Everything is about DataTable Object.
My problem is that I don't know where the exception is raised.
Let me explain.
Assume Column X has AllowDBNull property to false
And I'm not creating manually a new row that I add to the table
Which means I'm not using such code:
Dim NewRow as DataRow = DataTable.NewRow
NewRom.Item("X") = textbox1.text
DataTable.rows.add(NewRow)
If I was using that code, I would have indeed added the Try/Catch
Dim NewRow as DataRow = DataTable.NewRow
NewRom.Item("X") = textbox1.text
try
DataTable.rows.add(NewRow)
catch Ex as Exception
...
end try
I'm using a DataNavigator which adds in a hidden manner the new row to be added to the table.
So, if Column X is empty, he raises by himself the error. It's not an Exception to be handled. It's an error displayed at run time. Programmatically speaking, nothing went wrong at run time. It seems like DataTable object is designed with this feature and default Error Message.
I hope it's clear now.

Try catch if selected excel file is blank

Hello I have a program that imports an excel file using the oledb in vb.net. This program imports the excel spreadsheet into a datagridview. On opening the program will ask the user to choose an excel file to open, however if the user inputs nothing or presses the cancel button the program will crash. I'm trying to find a way to prevent a user from canceling or leaving the excel filename blank. I'm hoping this will be done using a try catch block but I'm not exactly familiar with try catch in vb.net. If anyone has any suggestions or solutions for this I would greatly appreciate it. This is what I found on MSDN.
If System.IO.File.Exists(filePath) = False Then
Console.Write("File Not Found: " & filePath)
Else
' Open the text file and display its contents.
Dim sr As System.IO.StreamReader =
System.IO.File.OpenText(filePath)
Console.Write(sr.ReadToEnd)
sr.Close()
End If
You could try a Try....Catch loop. Check this site out, should give you what you are looking for.
You could possibly use the Try....Catch loop and on the catch have an error message saying they must fill in the blank textbox.
I would suggest to take care of this at the source, when opening the file, and catching errors after the fact should be a last resort.
If filePath <> String.Empty And System.IO.File.Exists(filePath) Then
Try
'handle the opening of the file
Catch ex As Exception
Console.Write(ex.Message)
End Try
ElseIf filePath = String.Empty Then
Console.Write("Nothing Entered")
Else
Console.Write("File Not Found: " & filePath)
End If

Compiler warning: null reference exception

I have the following code in Visual Studio 2005.
Dim OutFile As System.IO.StreamWriter
Try
OutFile = New System.IO.StreamWriter(Filename)
// Do stuff with OutFile
Catch Ex As Exception
// Handle Exception
Finally
If OutFile IsNot Nothing Then OutFile.Close()
End Try
But VS2005 brings up the warning for the line "If OutFile IsNot.." that
Variable 'OutFile' is used before it has been assigned a value. A null reference exception could result at runtime.
Is there some way of removing this warning by subtly altering the code or is there just a better way of doing what I'm trying to do?
Thanks
Rob
Dim OutFile As System.IO.StreamWriter
OutFile = Nothing
Try
OutFile = New System.IO.StreamWriter(Filename)
// Do stuff with OutFile
Catch Ex As Exception
// Handle Exception
Finally
If OutFile IsNot Nothing Then OutFile.Close()
End Try
Similar to C# error: Use of unassigned local variable
Its a question of scope, the initialisation of the outfile object is happening in a block of code not visible to the fianlly block.
The accepted answer is correct, of course, but it doesn't explain why or when explicit initialization may matter.
VB.NET usually assigns a default value (0 or Nothing) when a variable is declared, but there are corner cases where it doesn't.
Consider this simple console application:
Sub Main()
For i As Integer = 1 To 5
Dim number As Integer
If i = 3 Then number = 3
Console.Write(number)
Next
End Sub
What's the output look like? You might expect that number gets set to 0 for every iteration of the loop, and it only gets set to 3 on the third iteration of the loop. Then for the fourth and fifth iteration, it'd be 0 again. So the output is 00300, right? Not so. The output of this code is actually
00333
That's because in VB.NET, the lifetime of a variable declared in a loop is for the whole loop, not for one iteration of the loop (Not what you'd expect, huh?). But if you explicitly set the value of number to 0 at its declaration, like so
Dim number As Integer = 0
then the output looks like
00300
So it's usually safe to assume VB.NET will set the default value when you Dim a variable, but it's always safest to set it explicitly to 0 or Nothing to get the expected behavior.