Null Pointer Null Pointer - 3 months ago 18
C# Question

Copy data from dataset to list Error

I'm getting some data from

Stored Procedure
to
DataSet
and then copying that data to a
List
. There are some
NULL
values in data and for that I'm checking with
DBNULL.Value
. But whenever it comes to a NULL value, it gives me error


ERROR : Specified cast is not valid.


This is my class definition.

public class CustomClass
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public int ZoneId { get; set; }
public string ShortName { get; set; }
public int CityId { get; set; }
public int ExpCenId { get; set; }
public int CategoryId { get; set; }
public double Charges { get; set; }

}


This is how I'm copying data from DataSet to List.

objResult.lst.Add(new CustomClass()
{
Code = dsLogin.Data[I]["Code"].ToString(),
Id = (int)dsLogin.Data[I]["Id"],
Name = dsLogin.Data[I]["Name"].ToString(),
ShortName = dsLogin.Data[I]["ShortName"].ToString(),
ZoneId = (int)dsLogin.Data[I]["ZoneId"],
CityId = (int)(dsLogin.Data[I]["CityId"] == DBNull.Value ? 0 : dsLogin.Data[I]["CityId"]),
ExpCenId = (int)(dsLogin.Data[I]["ExpCenId"] == DBNull.Value ? 0 : dsLogin.Data[I]["ExpCenId"]),
CategoryId = (int)(dsLogin.Data[I]["CategoryId"] == DBNull.Value ? 0 : dsLogin.Data[I]["CategoryId"]),
Charges = (double)(dsLogin.Data[I]["Charges"] == DBNull.Value ? 0.0 : dsLogin.Data[I]["Charges"])
});


In case of
NULL
, When I check
dsLogin.Data[I]["CityId"]
in immediate window, it shows me { } and when I check

(int)(dsLogin.Data[I]["CityId"] == DBNull.Value ? 0 : dsLogin.Data[I]["CityId"])


It shows 0 but when I try to copy this in CityId, It throws Exception.

I'm stuck over here and don't know what I'm doing wrong. Any Kind of help will be appreciated.

Answer

Try using IsCityIdNull() instead of DBNull. DataSet generates autmoatically null functions for all fields.

Or

Try Convert.ToInt32 instead of (int).