none
Cannot cast a SQL tinyint to [s]byte RRS feed

  • Question

  • I have SQL table data in a DataRowView from a DataTable, and I am attempting to cast what was a tinyint in the SQL table into either a byte or sbyte, but I get runtime errors of an illegal cast. What am I missing here? I can cast other SQL data types just fine with short/int/string/double/... but tinyint seems to require using Convert.ToByte(). Thanks for any pointers.
    • Edited by cgtyoder Friday, October 5, 2012 3:46 PM
    Friday, October 5, 2012 3:40 PM

Answers

  • Well, I figured out what was happening - I had a UNION of 2 SELECT statements, and in the second SELECT, the column in question was returning an int, causing the column for the whole result to of course be an int. So once I cast that 2nd SELECT column to a tinyint, all is well now.
    • Marked as answer by cgtyoder Wednesday, October 17, 2012 1:57 PM
    Wednesday, October 17, 2012 1:56 PM

All replies

  • Hi Cgtyoder,

    Welcome to the MSDN forum.

    Could you please provide some code snippet?

    Converting tinyint to byte should work, because they are 8-bit unsigned integer (0-255). The sbyte is Signed 8-bit integer (-128 to 127), so you will have the risk of losing data.

    Good day.


    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us

    Monday, October 8, 2012 3:28 AM
  • Well - not sure how much of a "code snippet" you want - but here is the "problem" line of code:

    byte rowBreakFlag = Convert.ToByte(timeRec[9]);

    ... will work, but

    byte rowBreakFlag = (byte)timeRec[9];

    gives a runtime exception. timeRec is of type DataRowView, and the MS SQL db the data was taken from is a tinyint column. The db is at Compatibility Level 100. I am compiling against .NET Framework 4 Client Profile.

    • Edited by cgtyoder Monday, October 8, 2012 5:54 PM
    Monday, October 8, 2012 5:53 PM
  • If it comes from DataRowView, have you checked what is the type of an object in timeRec[9]?
    Tuesday, October 9, 2012 5:41 AM
  • timeRec[9].GetType() results in Int32. No idea why. Guess I'll have to live with that.
    Tuesday, October 9, 2012 1:46 PM
  • Well, I figured out what was happening - I had a UNION of 2 SELECT statements, and in the second SELECT, the column in question was returning an int, causing the column for the whole result to of course be an int. So once I cast that 2nd SELECT column to a tinyint, all is well now.
    • Marked as answer by cgtyoder Wednesday, October 17, 2012 1:57 PM
    Wednesday, October 17, 2012 1:56 PM