Wednesday, May 16, 2012

Specified cast is not valid when getting Datatable Column Value

The above error message appears when I am trying to get Column Value from Datatable.



This is what I find in the stacktrace:




System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()

at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable
1
source)




 and this in the TargetSite when debugging:



{ Boolean b__0(System.Data.DataRow)}




Here is my code:
DataTable hr = new DataTable();



            hr.Columns.Add("BookingDate");
hr.Columns.Add("BookingId");
hr.Columns.Add("BookingSource");
hr.Columns.Add("CheckInDate");
hr.Columns.Add("CheckOutDate");


for (int i = 0; i < gmisc.GetModifiedBookings(gmoreq).Bookings.Length; i++)
{
hr.Rows.Add();
hr.Rows[i]["BookingDate"] = Convert.ToDateTime(gmisc.GetModifiedBookings(gmoreq).Bookings[i].BookingDate.ToString());
hr.Rows[i]["BookingId"] = Convert.ToInt64(gmisc.GetModifiedBookings(gmoreq).Bookings[i].BookingId.ToString());
hr.Rows[i]["BookingSource"] = gmisc.GetModifiedBookings(gmoreq).Bookings[i].BookingSource.ToString();
hr.Rows[i]["CheckInDate"] = Convert.ToDateTime(gmisc.GetModifiedBookings(gmoreq).Bookings[i].CheckInDate.ToString());
hr.Rows[i]["CheckOutDate"] = Convert.ToDateTime(gmisc.GetModifiedBookings(gmoreq).Bookings[i].CheckOutDate.ToString());



}
Int64 BookingId = (from DataRow dr in hr.Rows
where (Int64)dr["BookingId"] == BookId
select (Int64)dr["BookingId"]).FirstOrDefault();
TextBox1.Text = Convert.ToString(BookingId);


Where did I go wrong, if somebody can please tell me.





No comments:

Post a Comment