Wednesday, March 28, 2012

System.InvalidCastException: Specified cast is not valid.

I have an table with a field of bit. the fields name is Active.
When trying to add that field to a label it gives me the following.
It all works when not using this field.

Error : System.InvalidCastException: Specified cast is not valid.
get {
Line 2057: try {
Line 2058: return ((bool)(this[this.tableJob_Posts.ActiveColumn]));
Line 2059: }
Line 2060: catch (System.InvalidCastException e) {

My code is as follows.

jpDT = jpTA.GetJob_PostsByJobID(jid);

foreach (DataSet1.Job_PostsRow jprin jpDT)

{

if (jpr.Active !=null)

{

this.ActiveLabel.Text = jpr.Active.ToString();

}

Is this field nullable in the database, and are you using TableAdapters? If so, can't simply check for null. You need to instead call the method IsActiveNull() which will be auto-generated by your row class if the field is nullable. This will then check for DbNull instead of null.

0 comments:

Post a Comment