简体   繁体   中英

how to convert a data type avoiding System.FormatException?

Im trying to receive a string an convert it in integer, the code is this:

        int menu = 3
        int orden = 0;
        string query = @"select max(oppord)+1 as orden
                         from rhlibry.vaoppfi
                         where pincor = " + menu;
        OdbcConnection cn = new OdbcConnection("dsn=RHLIBRY;uid=PC00;pwd=PC00;");
        OdbcCommand cmd = new OdbcCommand(query, cn);
        cn.Open();
        OdbcDataReader oa = cmd.ExecuteReader();
        while (oa.Read())
        {
            orden = Int32.Parse(oa["orden"].ToString());
        }
        return orden;

the sql query return "orden" in string format, and I need transform it to integer.

The line orden = Int32.Parse(oa["orden"].ToString()); returns a error of type System.FormatException.

Why? I do wrong?

Help me please !

Thanks

This is probably because your query returns null value.

Suppose you have a Category table that have an Id column with values 1,2,3. If you run this query:

SELECT Max(Id)+1 As Id From Category WHERE Id = -1

You will receive this result:

Id
----------
NULL

So when you use Int32.Parse(oa["Id"].ToString()) you will receive a FormatException.

As a fix you can use:

SELECT ISNULL(Max(Id),0)+1 As Id From Category WHERE Id = -1

Also if your business logic allows, you can remove criteria.

Also in C# side, you can use int.TryParse():

int id = 0;
var idObject= oa["Id"];
if (idObject!=null)
   int.TryParse(oa["Id"].ToString(), out id);

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