Hi..
I am new to c#. I want to write common procedure , when I pass database field as a parameter to procedure, if field has value just return the value or if field type is numeric then reurn 0 or if it is string then return ""..depending upon datatype of field being passed.
Something like this considering CheckNull is the name of procedure..
txtCode.Text=CheckNull(rs.Fields["ID"]);
txtDate.Text=CheckNull(rs.Fields["SaleDate"]);
txtYear.Text=CheckNull(rs.Fields["NoofYears"]);
Loading

Dave131 reputationPosted Dec 27, 2007, 6:07 PM EST
ca guy13 reputationPosted Dec 27, 2007, 7:32 PM EST
Dave131 reputationPosted Dec 27, 2007, 10:23 PM EST
I cannot think of a way off the top of my head for a method that will be able to check for both value types and reference types. But here is a suggestion for checking for nulls:
private bool CheckNull(Object anObject)
{
}
You could call this with something like:
bool isItNull = CheckNull(instanceDataReader.GetValue());
If the line if(anObject == null) does not work, you could try if(anObject is DBNull)
I have not tested my suggestions, so no guarantees that they'll work.
ca guy13 reputationPosted Jan 2, 2008, 12:52 PM EST
Posted Jan 2, 2008, 1:23 PM EST
Strings are reference type variables, while integers are value types. You could try doing something like:
if(myVar.GetType().IsValueType)
//Do something
else
//Do something else
Dave131 reputationPosted Jan 4, 2008, 4:11 PM EST
You could write overloaded methods. Another idea would be to use a switch statement.
Something like:
ca guy13 reputationPosted Jan 8, 2008, 8:25 AM EST
Yes ..sorry I meant Overloading. I have been using delphi..new to c#. In example you gave here you are returning only datatype as string. Is this possible? What return data type I need to give here?
private string CheckValue(Object theDBObject)
{
switch (theDBObject.GetType().ToString())
{
case "System.int32": return 0;
case "System.String": return "";
...
default: break;
}
}
Posted Jan 8, 2008, 10:23 AM EST
{
switch (theDBObject.GetType().ToString())
{
case "System.Int32":
return 0;
case "System.String":
return String.Empty;
...
default:
break;
}
}
Then just cast the object back to what you need it to be using a TryParse method.
ca guy13 reputationPosted Jan 8, 2008, 1:44 PM EST