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

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.

Related

How to update an MS Access database using a dataset in visual basic?

Hi I am currently working on a project on visual Basic 2010, what i am stuck on now is updating my MS Access database triggered by a button click.
I already have the connection and data adapter established and i generated a data set for the data adapter, and i have used the data set. what i am trying to do is read from a data grid view entries the user have typed in and save these changes to the data set, and finally save the dataset back into the database using the oledbdataadapter.update(dataset) command. I tried everything and i have been stuck for a while, there are no errors in the code and I can see the changes made to the dataset are successful and i can view them (i am getting the "update successful" at the end of the try so i am sure the code is executing till then and not going to exception), but i simply don't see the changes in the database.
below is the code, i will appreciate any help you can offer thank you.
For j As Integer = 6 To DataGridView1.Rows.Count
Try
Dim s As String = DataGridView1.Rows(j).Cells(0).Value
Dim Quantaties As Integer = DataGridView1.Rows(j).Cells(3).Value
For i As Integer = 0 To DataSet21.Tables("Stock").Rows.Count
Dim foundRow As DataRow = DataSet21.Tables("Stock").Rows.Find(i)
If foundRow IsNot Nothing Then
If foundRow(1) = s Then
DataSet21.Tables("Stock").Rows(i).Item(7) = Quantaties
DataSet21.AcceptChanges()
Try
Dim builder As New OleDbCommandBuilder(OleDbDataAdapter1)
Me.Validate()
OleDbDataAdapter1.UpdateCommand = builder.GetUpdateCommand()
OleDbDataAdapter1.Update(DataSet21.Stock)
DataSet21.AcceptChanges()
MsgBox("Update successful")
Catch ex As Exception
MsgBox("Update failed")
End Try
End If
End If
Next
BindingSource1.EndEdit()
Catch ex As Exception
End Try
Next
thank you for your reply.
I guess both ways work OleDbDataAdapter1.Update(DataSet21.Stock) and OleDbDataAdapter1.Update("DataSet21"), because i figured out what was wrong with my code. the problem was in the DataSet21.AcceptChanges() i should not have placed it before the OleDbDataAdapter1.Update(DataSet21.Stock).
the OleDbDataAdapter.update() saves changes done in the dataset to the database and the dataset.acceptchanges() makes the dataset save the changes done to it making it seem that it doesn't have changes in it anymore. so the OleDbDataAdapter.update() was not executing since the dataset didn't have changes done to it because of the dataset.acceptchanges()
so what i did was remove dataset.acceptchanges() and it finally worked. my code looks like this now.
For j As Integer = 6 To DataGridView1.Rows.Count
Try
Dim s As String = DataGridView1.Rows(j).Cells(0).Value
Dim Quantaties As Integer = DataGridView1.Rows(j).Cells(3).Value
For i As Integer = 0 To DataSet21.Tables("Stock").Rows.Count
Dim foundRow As DataRow = DataSet21.Tables("Stock").Rows.Find(i)
If foundRow IsNot Nothing Then
If foundRow(1) = s Then
DataSet21.Tables("Stock").Rows(foundRow(0) - 2).Item(7) = Quantaties
Try
BindingSource1.EndEdit()
OleDbDataAdapter1.Update(DataSet21.Stock)
MsgBox("Update successful")
Catch ex As Exception
MsgBox("Update failed")
End Try
End If
End If
Next
Catch ex As Exception
End Try
Next

FileExist not working vb.net

I really can not understand why the exception is triggered.
I created this code that performs some checks for the correctness of the license.
The function isittrial occurs if the trial software is creating a hidden file, this file is then checked with File.exist.
The problem is the following:
the file is created by isittrial but for some strange reason you enable the exception of file.exist, what can I do to fix it?
I really can not understand why it does not work.
isittrial() 'this function make the file to check
Dim percorsoCompleto As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
Try
If My.Computer.FileSystem.FileExists(directory) Then
Dim fileReader As String
Dim dire As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
fileReader = My.Computer.FileSystem.ReadAllText(directory,
System.Text.Encoding.UTF32)
Dim check = DeCryptIt(fileReader, "aspanet")
Dim datadecripted As String = DeCryptIt(Registry.GetValue("HKEY_CURRENT_USER\Software\cc", "end", ""), "aspanet")
If Date.Now < check And check <> datadecripted Then
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
Else
End If
Else
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
End If
Catch ex As Exception
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
'DeActivate()
'ForceActivation()
End Try
This line
If My.Computer.FileSystem.FileExists(directory) Then
seems to test for the existence of a file passing the name of a directory (or an empty string or whatever, we can see how this variable is initialized). In every case the result will be false.
Then your code jumps to an else block with the same error message of the exception fooling your perception of the error.
Try instead
Dim percorsoCompleto As String = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
percorsoCompleto = Path.Combine(percorsoCompleto, "Software", "cc.txt")
Try
If My.Computer.FileSystem.FileExists(percorsoCompleto) Then
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(percorsoCompleto,
System.Text.Encoding.UTF32)
.....
Notice that I have removed the path concatenation with a more fail safe call to Path.Combine

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

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.

system.NullReferenceException: Object not set to an instance of an object

Dim Permission As String
Dim chk As String = "p"
Permission = (ds.Tables("privilege").Rows(0).Item(0)).ToString
MessageBox.Show(Permission)
Dim PermissionArray() As String = Split(Permission, ":")
For i As Integer = 0 To 36
If PermissionArray(i) = 1 Then
Try
Dim chkBox As CheckBox = CType(Me.Controls(chk & i), CheckBox)
chkBox.Checked = True
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End If
Next
This code gives me the following error in catch, i have googled but nothing is working
This is the error: System.NullReferenceException – Object reference not set to an instance of an object.
As you noted chkBox.Checked throws NullReferenceException, you should evaluate the following line for the error:
Dim chkBox As CheckBox = CType(Me.Controls(chk & i), CheckBox)
' This may throw NullReferenceException if there is no (chk & i) control available
chkBox.Checked = True
Although it turned out not to be your problem this time,
Permission = (ds.Tables("privilege").Rows(0).Item(0)).ToString
is a prime candidate for a system.NullReferenceException. This statement relies on everything in your data set being fully and correctly populated or errors can occur.
If the table "privilege" does not exist in the dataset, or the table is empty, or the first column of the first row is null, you can get exceptions and it will be very hard to tell what is wrong. You should test those conditions before relying on the assignment, so you don't get exceptions.
I'll bet you are missing one or more controls "p0" ... "p35" since blindly build the ID, ask the form for the control of that ID but never check if it was actually found. Try including the value of 'i' in your message when the exception is caught. That'll be the first control you're misisng.
And then, be sure to check the return values of functions you call before you USE those return values.

How to continue insert if one row fails

I have a while loop where it fetches record from csv and inserts to sql table. Now csv may contain many rows.
What I want is if one row fails just log to a file and continue with next record. I was thinking of try and catch but that will exit the program. So, any suggestions?
while (csv.readnextline)
'assign csv columns to objects
try
'insert to db
Catch ex As Exception
'write to log file
End Try
I need the above code to continue after catching an exception.
Thanks
Try and catch do not exit the program, they just control the flow of the code in case something exceptional happens.
When an exception happens in the try block, the execution continues on the first line of the (corresponding) catch block. After the execution of the catch block, the code continues on the first line after the catch, which in your case could be the End While which will continue the loop.
So an construction like this
While dr.Read
Try
InsertRowIntoDataBase()
Catch ex As Exception
LogErrorToFile(ex)
End Try
End While
should work for you.
However, this is a bad design, as it will generate and log an exception, no matter what the problem is, whether the data is invalid, or the sql server is down, or even if there is an error in your code (e.g. some lurking NullReferenceException). You should limit the handling of exception to a specific case, e.g. to a problem with the database, like this:
While dr.Read
Try
InsertRowIntoDataBase()
Catch ex As SqlClient.SqlException
LogDataBaseErrorToFile(ex)
End Try
End While
Also, if there are known possible problems with the data (e.g. a string in the csv where an integer is expected) it's better to just check that than to use an exception mechanism, something along these lines:
While dr.Read
Try
If Not IsRowValid() Then
LogInvalidDataToFile()
Continue While
End If
InsertRowIntoDataBase()
Catch ex As SqlClient.SqlException
LogDataBaseErrorToFile()
Catch ex As Exception
LogGenericErrorToFile()
End Try
End While
no it won't exit the program, depending on how/where you handle the exception. If you do something like :
Dim WrongValuedLinesList As New List(Of String)
Dim ConversionFailedList As New List(Of String)
Dim InsertionFailedList As New List(Of String)
Dim NumberOfInsertedLines As integer = 0
For Each (CurrentLine in my csv)
' 1. line processing
Try
' (process my line : split, convert, check range...)
If (I know the insertion will fail) Then
' (Store information about that wrong line, in List, log, or do nothing)
WrongValuedLinesList.Add(" This line : " & CurrentLine
& " has wrong values because...
Continue For
End If
Catch ex as exception
' (here handle the line conversion failed : store in list, or log, or do nothing ...)
' for expl :
ConversionFailedList.Add(" Conversion failed for line " & CurrentLine
& " exception details : " & ex.message " )
End Try
' 2. Line insertion
Try
'(insert my processed data into database)
NumberOfInsertedLines +=1
Catch ex as exception
' (here handle the insertion failed exception (expl : primary key might not be unique)
' : store in list, log, do nothing...)
' for example :
InsertionFailedList.Add(" Insertion failed for line " & CurrentLine
& " exception details : " & ex.message " )
End Try
Next
(Here you might wanna report how things went to your user using
your error list.)