[Mono-devel-list] Another C# ?: InvalidCastException

Rafael Teixeira monoman at gmail.com
Mon Dec 13 10:06:51 EST 2004

All fields are Not Null in the database? If not you can't cast then
directly, you have to check if they are null, because in that case
they are a dbnull object not a string and surely not a boxed integer
to be cast.

// out of loop

  int ord_deptime = reader.GetOrdinal("deptime");
  int ord_depqty = reader.GetOrdinal("depqty");

// in the loop

  if (reader.IsDBNull(ord_deptime))
    deptime = String.Empty; // or deptime = null;
    deptime = reader.GetString(ord_deptime);
  if (reader.IsDBNull(ord_depqty))
    depqty = 0;
    depqty = reader.GetInt32(ord_depqty);

Alternatively you can define deptime, depqty, etc... as SqlString,
SqlInt32, etc.. that are structs that receive the value and the null
state of the column, but it may have some undesirable impact in the
rest of your program.

Hope it helps,

On Sun, 12 Dec 2004 12:59:50 -0600, Eric Scott
<scottclansman at cwazy.co.uk> wrote:
> Hey, once again I apologize for plopping newbie C# questions into this
> list; if you know of a list that might be better suited for C#
> newbie-ish stuff, let me know!
> So I'm tinkering (again) with PostGreSQL access from C#.  I'm getting
> the data from the database and putting it into my variables.... and
> something goes haywire. Here's the code section:
> <yammer>
> string sql =
>            "SELECT deptime, depqty, depsite, descrip, arvtime, arvqty,
> arvnote " +
>            "FROM log";
>        dbcmd.CommandText = sql;
>        IDataReader reader = dbcmd.ExecuteReader();
> <snip>
> //(In a while loop here)
>             deptime = (string) reader["deptime"];
>             depqty = (int) reader["depqty"];
>             depsite = (string) reader["depsite"];
>             descrip = (string) reader["descrip"];
>             arvtime = (string) reader["arvtime"];
>             arvqty = (int) reader["arvqty"];
>             arvnote = (string) reader["arvnote"];
> </yammer>
> Okay, compiles fine.  But when I run the exe I get:
> > Unhandled Exception: System.InvalidCastException: Cannot cast from
> > source type to destination type.
> > in <0x0029c> Test:Main (string[])
> The "deptim" and "depqty" lines execute fine, as does the "arvqty" line,
> but all the other strings give this error.   All of the values being put
> into strings are varchar(32) in the databased, and all the variables
> have been declared as int or string, respectively.
>      Thanks,
>            ES
> _______________________________________________
> Mono-devel-list mailing list
> Mono-devel-list at lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-devel-list

Rafael "Monoman" Teixeira
Just the 'crazy' me in a sane world, or would it be the reverse? I dunno...

More information about the Mono-devel-list mailing list