开发者

Int inadverantly cast to string behind my back

开发者 https://www.devze.com 2023-02-08 23:25 出处:网络
This was originally a problem with Crystal Reports but I tracked down the issue to a single line of code:

This was originally a problem with Crystal Reports but I tracked down the issue to a single line of code:

foreach (DataRow dr in ds.Tables["CurrentScheduleFields"].Rows)
    if (dr["MY_FIELD"].ToString() == string.Empty)
        dr["MY_FIELD"] = 0;

I am using an Oracle database. The field is actually a Numeric(2). We are using straight ADO.NET and no Nullable types in this case. In one case, the field in question has a value of an int and the above line of code is fine. The other case, the value of the field is DBNull.Value, and 开发者_运维百科the above or something is converting the 0 to "0" ( a string).

dr is not a `DataReader foreach (DataRow dr in ds.Tables["CurrentScheduleFields"].Rows)

Does anyone know why?

My browser is not letting me click on the Add Comments, so I am adding stuff here. Why can't I do if (dr["MY_FIELD"] == DBNull.Value) dr["MY_FIELD"] = 0; the debugger hits that and converts to a string with a value of "0", not 0. I guess the first answer handles this, "So the problem may be that the first "MY_FIELD" is null, convincing ADO.NET that the type for that column is a string." So it's now string with DBNull.Value in it?

My browser is locked down. I can't click on anything except edit this but: ANSWER: Handle this on the Crystal side by changing the formula to handle a string for this value and not an int. It works!


In some cases, when dealing with DataTable, I've seen it try to "guess" at the type of a column based on the value in that column in the first row in your set. So the problem may be that the first "MY_FIELD" is null, convincing ADO.NET that the type for that column is a string.

You may want to set the schema for your DataTable before you try to load it.

0

精彩评论

暂无评论...
验证码 换一张
取 消