views:

121

answers:

7

Hi, I have some dataset with values and now I need to put that values into textbox but there is some decimal and double type values so I need to cast them toString() and it happens that sometime dataset values are empty so before casting toString() I need to check Is there any value ??? This is sample line:

I need something like this :

if(ds.Tables[0].Rows[0].Field<decimal>("IndexPrethodni") !=null or something)
{
  Convert.ToString(ds.Tables[0].Rows[0].Field<decimal>("IndexPrethodni"));
}

I known decimal is not nullable type , but is there any easy solution to check this srt of values ?????

+2  A: 

Try

if(ds.Tables[0].Rows[0]["IndexPrethodni"] != DBNull.Value)

You can also check the value using Convert.IsDBNull().

svanryckeghem
this works great :))
zire
+1  A: 

TO use Convert.ToString you need not to check for null value, because if there will null then also it will not give any error and return blank..

Rajesh Rolen- DotNet Developer
+1  A: 

You need to check the value isnt DBNull, so something like this would work

object columnValue = ds.Tables[0].Rows[0].Field<decimal>("IndexPrethodni");
if (object != System.DBNull.Value) Convert.ToString(columnValue);
PaulG
+3  A: 

Personally, I'd wrap it like so:

        var col = ds.Tables[0].Columns["IndexPrethodni"];
        var row = ds.Tables[0].Rows[0];
        if (!row.IsNull(col))
        {
            string s = row[col].ToString();
            ...
        }

(the "via a column object" is the most direct (= fastest) indexer)

Marc Gravell
As always, I learn something from you.
Chris Lively
+1  A: 

check for DBNull

if(ds.Tables[0].Rows[0].Field("IndexPrethodni") != DBNull.Value) { //convert to string }

Chaitanya
+1  A: 

I normally use a method such like:

public T GetValue<T>(object source)
{
  if (Convert.IsDBNull(source))
    return default(T);

  return (T)source;
}

E.g.

using (var reader = command.ExecuteReader())
{
  if (reader.Read())
  {
    return GetValue<string>(reader["SomeColumn"]);
  }
}
Matthew Abbott
+1  A: 

Why don't you use the nullable type to check for a value?

if( ds.Tables[ 0 ].Rows[ 0 ].Field<decimal?>( "IndexPrethodni" ).HasValue )
{
   Convert.ToString( ds.Tables[ 0 ].Rows[ 0 ].Field<decimal>( "IndexPrethodni" ) );
}
Viper