C# parse string “0” to integer

前端 未结 8 950
抹茶落季
抹茶落季 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: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?

提交回复
热议问题