How to handle null values

ADO.NET, a robust framework for data access in .NET, facilitates seamless connectivity between relational and non-relational systems by employing a standardized collection of components. Within ADO.NET, the classes are organized into two fundamental components: the Data Providers, responsible for interacting with the underlying databases, and the DataSet, which serves as an in-memory representation of data and offers powerful data manipulation capabilities. Through the combined functionality of these components, ADO.NET empowers developers to efficiently manage and manipulate data across diverse systems.

In certain scenarios, when working with Dataset and attempting to read data from it, you may encounter error messages such as the following:

Conversion from type 'DBNull' to type '<DataType>' is not valid

To handle DBNull values in your code, you can use the DBNull class. It is used to represent a nonexistent value. You can check if a value is DBNull by using the IsDBNull function, which returns True if the expression's data type evaluates to DBNull, and False otherwise.

If IsDBNull(ds.Tables(0).Rows(i).Item(0)) Then MsgBox("DBNULL exist in the field ") Else MsgBox(CInt(ds.Tables(0).Rows(i).Item(0))) End If

In the provided code snippet, the IsDBNull function is used to check whether the value of a Dataset is DBNull or not. This function evaluates the data type of the expression and returns True if it is DBNull, indicating a nonexistent value, and False if it is not DBNull. By using this function, you can handle DBNull values appropriately in your code.

Full Source VB.NET
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "your sql select statements here" connection = New SqlConnection(connetionString) connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds) connection.Close() Try If IsDBNull(ds.Tables(0).Rows(i).Item(0)) Then MsgBox("DBNULL exist in the field ") Else MsgBox(CInt(ds.Tables(0).Rows(i).Item(0))) End If Catch ex As Exception MsgBox(ex.ToString()) End Try End Sub End Class