C# parse string “0” to integer

前端 未结 8 946
抹茶落季
抹茶落季 2021-01-18 02:58

I have a new laptop at work and code that worked earlier in the week does not work today.

The code that worked before is, simplified:

while (dr.Read         


        
相关标签:
8条回答
  • 2021-01-18 03:32

    I think it's generally not considered a good idea to call Convert.ToInt32 for the value reading out of database, what about the value is null, what about the value cannot be parsed. Do you have any exception handling code here.

    1. Make sure the value is not null.
    2. Check the value can be parsed before call Int32.Parse. Consider Int32.TryParse.
    3. consider use a nullable type like int? in this case.

    HTH.

    0 讨论(0)
  • 2021-01-18 03:34

    are you checking for null ?

    if(!dr.IsNull("FieldName")){
       int i = Convert.ToInt32(dr["FieldName"]))
    }
    
    0 讨论(0)
  • 2021-01-18 03:35

    you should check dr["FieldName"] != DBNull.Value and you should use TryParse if it passes the DBNull test...

    if ( dr["FieldName"] != DBNull.Value )
    {
        int val = 0;
        if ( int.TryParse( dr["FieldName"], out val ) )
        {
            i = val;
        }
        else
        {
            i = 0; // or some default value
        }
    }
    
    0 讨论(0)
  • 2021-01-18 03:44

    I have seen this issue crop up with .NET Double class, parsing from string "0" as well.

    Here's the really wacky part: you can get past the issue by using a different user account to run the program, and sometimes if you destroy and re-create the current user account on the machine, it will run fine.

    I have yet to track this down, but you might get past it this way at least.

    0 讨论(0)
  • 2021-01-18 03:48

    Edit:
    @Mike's response made me think that is extremely odd behavior and a simple google search yielded this result: int.Parse weird behavior

    An empty string would also cause this issue.

    You could check for dbnull before parsing, also it is good to validate parsed data.

    You could use a default value and TryParse..

    int i = -1;
    if(!int.TryParse(dr["MyColumn"] as string, out i))
       //Uh Oh!
    

    Edit:
    I posted this as a comment in @Chris' answer, but if the sql datatype is int then why not just use the GetInt32 method on the DataReater instead of retrieving it as a string and manual parsing it out?

    0 讨论(0)
  • 2021-01-18 03:49

    Are you sure it's "0" and not "null"? What exception do you get?

    EDIT:

    Just out of curiosity, if it is really faulting on int.Parse("0"), can you try int.Parse("0", CultureInfo.InvariantCulture);?

    Otherwise, post your query. Any joins?

    0 讨论(0)
提交回复
热议问题