Bangla Tiger
Bangla Tiger

Reputation: 89

Checking if a datatable column has value or not in C#

This is my datatable

DataTable get_order_info = objDUT.GetDataTable("select * from investment_orders where order_id =" + dr["order_id"]); 

In this datatable there is a column added_date.

I want to apply my method if the column added_date != null

I have written this code :

if (get_order_info.Columns.Contains("added_time") != null)
{
    var secondsSince1970 = DateTime.Now - DateTime.Parse("01.01.1970 00:00:00");
    difference = Convert.ToInt64(secondsSince1970.TotalSeconds) - Convert.ToInt64(get_order_info.Rows[0]["added_time"]);
}
else
{
    Label1.Text = "fail";
}

but it is showing an error

Input string was not in a correct format

Please help me.

Upvotes: 0

Views: 3784

Answers (2)

Andrew Taylor
Andrew Taylor

Reputation: 82

Assuming that what you are wanting to do is to actually determine if the field has a value, you would need to do the following:

foreach(DataRow row in myTable.Rows)
{
    if (row.Table.Columns.Contains("added_time") && !DBNull.Value.Equals(row["added_time"])) 
    { 
         DateTime theValue = (DateTime)row["added_time"];

    }
}

Upvotes: 0

Lukasz M
Lukasz M

Reputation: 5723

Answering only to fix the error message You mentioned, it seems You used wrong DateTime format. Try to change:

DateTime.Parse("01.01.1970 00:00:00");

into:

DateTime.Parse("1970-01-01 00:00:00", System.CultureInfo.Globalization.InvariantCulture);

As an alternative, You can explicitly specify format You want to use:

DateTime.ParseExact("01.01.1970 00:00:00", "dd-MM-yyyy HH:mm:ss", System.CultureInfo.Globalization.InvariantCulture);

Upvotes: 2

Related Questions