简体   繁体   中英

Specified cast is not valid when casting from int32 to int16

Convert.ToInt16(row["INT"] as Int16?); returns 0 and (Int16)row["INT"]; throws an exception Specified cast is not valid.

    private DataTable GetTableWithValue()
    {

        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[] { 
            new DataColumn("INT", typeof(Int32)),
            new DataColumn("STRING", typeof(string )),
            new DataColumn("DATETIME", typeof(DateTime )),
            new DataColumn("BOOLEAN", typeof(bool)),
        });

        dt.Rows.Add(dt.NewRow());

        dt.Rows[0][0] = 10;
        dt.Rows[0][1] = "Babu";
        dt.Rows[0][2] = DateTime.Now;
        dt.Rows[0][3] = true;
        return dt;
    }


        dt = GetTableWithValue();
        row = dt.Rows[0];


        int? INT = (row["INT"] as int?); //10
        Int16? INT16 = Convert.ToInt16(row["INT"] as Int16?); //0
        Int16 = (Int16)row["INT"]; //Specified cast is not valid. 

row["INT"] as Int16? returns null when either the provided value within the row is zero, or when the value from the row is not castable to Int16 (for example if the content was "zero" ). Convert.ToInt16(null) now returns zero .

However the "direct" cast (Int16) myValue throws an exception when the cast fails. See here for more details

Anyway in your code you´re trying to cast an Nullable<int> to Int16 which is obviously not possible. You can however use the nullables value , which is an int :

Int16 result = ((int?)row["INT"]).Value;

EDIT: A quite better aproach would be to use TryParse which won´t throw an exception if parsing fails but simply returns false :

Int16 result;
if (Int16.TryParse(row["INT"].ToString(), out result))  
{
    // do something with result
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM