我正在从数据库中获取数据并将其填充到域object.Lets中
public class A
{
int? ai;
public int? AI
{
get { value = ai;}
Set { ai = value; }
}
}所以我在主类中创建域对象。
class TestClass
{
static void Main(string[] args)
{
class A objData = new A();
// here some logic for creating connection to the database and calling the datareader to fetch the //data.
int temp =(int) objDataReader["aiDAta"];
objData.ai = temp == null? 0: temp;
func(objData);
}
}
public void func(A objData)
{
// Here i want to display the value of objData.ai only if its database value is not null.since i was //already assigned 0,if the value from the database is null...how can i able to identify whether the value //from the database is null or not? also,In database "aiDAta" will have the value range from 0 - 99.
}}
这里我只想显示objData.ai的值,如果它的数据库值不是null.since,我已经被分配了0,如果数据库中的值是null...how,我能识别数据库中的值是否为空吗?另外,在数据库"aiDAta“中,值的范围是0- 99。
发布于 2011-06-21 03:43:44
将objData.ai与
DBNull.value而不是NULL
或
检查
IsDBNull(objData.ai)或
public Int32 TryCastInteger32(object value)
{
if (value != null && !Information.IsDBNull(value)) {
Int32 retVal = default(Int32);
if (Int32.TryParse(value.ToString(), out retVal)) {
return retVal;
}
}
return 0;
}发布于 2011-06-20 19:36:52
如果强制转换为Nullable,则检查HasValue属性。仅当值类型不为空时才为真。
发布于 2011-06-20 20:10:20
通常将空DB字段作为System.DbNull返回,在这种情况下,以下转换将失败:
int temp =(int) objDataReader["aiDAta"]; 在使用之前,可以使用DBDataReader's IsNull方法检查是否为空值
https://stackoverflow.com/questions/6410503
复制相似问题