Say I have this string variable containing a value from an SQL query stored in a variable like so:
string strDesc = ds.Tables[0].Rows[0]["Description"].ToString();
and as its a string it works ok
what about if I had field types in a database that where of type int and money, how would I apply it like above? Would it be somthing like below with a conversion applied?:
int field I want to keep it as an int
int strOrderID = ds.Tables[0].Rows[0]["OrderID"];
money field I want to keep as type money
decimal strPrice = ds.Tables[0].Rows[0]["Price"];
Thanks in advance for any answers provided
I suggest to use the strongly typed Field
extension method which also supports nullable types:
int orderID = ds.Tables[0].Rows[0].Field<int>("OrderID");
decimal price = ds.Tables[0].Rows[0].Field<decimal>("Price");
Assuming that Price
can be NULL
, you can cast it to a Nullable<decimal>
easily:
decimal? price = ds.Tables[0].Rows[0].Field<decimal?>("Price");
if(price.HasValue) Console.WriteLine(price.Value);
By the way, the old way would be simple casting:
int orderID = (int) ds.Tables[0].Rows[0]["OrderID"];
However, if you use this query more than once and you're selecting a single table or at least fields that belong together, you should consider to create a class with these properties. Then your code becomes much more readable, reusuable and maintainable.
public class Order
{
public int OrderID { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public override bool Equals(object obj)
{
Order o2 = obj as Order;
if (o2 == null) return false;
return OrderID == o2.OrderID;
}
public override int GetHashCode()
{
return OrderID;
}
public override string ToString()
{
return Description;
}
}