Handle Boolean null value from Database using C# and VB.Net in ASP.Net

Last Reply one month ago By dharmendr

Posted one month ago

Hi Team 

How to handle boolean null value conditional operator

example is below 

I have datatatable like 

Id Gender  
1 null  
2 Null  

Gender= Convert.ToBoolean(dr["Gender].ToString())

I am getting error

if Gender is null will show as 0


Like nullable type

Gender= Convert.ToBoolean(dr["Gender].ToString())??null: 0;




You are viewing reply posted by: dharmendr one month ago.
Posted one month ago

Hi amar,

Refer below sample.


<asp:GridView runat="server" ID="gvDetails"></asp:GridView>



using System.Configuration;
using System.Data;
using System.Data.SqlClient;


Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient



protected void Page_Load(object sender, EventArgs e)
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "SELECT * FROM Gender";
    using (SqlConnection con = new SqlConnection(conString))
        SqlCommand cmd = new SqlCommand(query);
        using (SqlDataAdapter sda = new SqlDataAdapter())
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (DataTable dt = new DataTable())
                List<GenderData> datas = new List<GenderData>();
                foreach (DataRow dr in dt.Rows)
                    GenderData data = new GenderData();
                    data.Id = Convert.ToInt32(dr["Id"]);
                    data.Gender = Convert.ToBoolean(dr["Gender"] != DBNull.Value ? Convert.ToString(dr["Gender"]) : "false");

                gvDetails.DataSource = datas;

public class GenderData
    public int Id { get; set; }
    public bool Gender { get; set; }


Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim query As String = "SELECT * FROM Gender"
    Using con As SqlConnection = New SqlConnection(conString)
        Dim cmd As SqlCommand = New SqlCommand(query)
        Using sda As SqlDataAdapter = New SqlDataAdapter()
            cmd.Connection = con
            sda.SelectCommand = cmd
            Using dt As DataTable = New DataTable()
                Dim datas As List(Of GenderData) = New List(Of GenderData)()
                For Each dr As DataRow In dt.Rows
                    Dim data As GenderData = New GenderData()
                    data.Id = Convert.ToInt32(dr("Id"))
                    data.Gender = Convert.ToBoolean(If(dr("Gender") IsNot DBNull.Value, Convert.ToString(dr("Gender")), "false"))
                gvDetails.DataSource = datas
            End Using
        End Using
    End Using
End Sub

Public Class GenderData
    Public Property Id As Integer
    Public Property Gender As Boolean
End Class