简体   繁体   中英

Error casting CHAR(1) SQL column as “char” in code

I'm selecting from a SQL Server 2000 box CHAR(1) column called Combo_Label - it will always have a single A .. Z character in there. During testing, it will convert the first 70 or so items with no problem, but then runs into a Invalid Cast Exception .

This is the problem line:

char comboLabel = (char)formCombo.Rows[j]["Combo_Label"];

This is a screenshot of the watch list showing some ways it can be evaluated.

http://i.imgur.com/iaEBEDZ.png

Any thoughts as to why this occurs?

The database and the Db access APIs have no concept of char . Your CHAR(1) is mapped to string .

probably the most sensible option:

  string comboLabel = (string)formCombo.Rows[j]["Combo_Label"];

but if you really want a char :

  char comboLabel = ((string)formCombo.Rows[j]["Combo_Label"])[0];

该字段是一个字符串,您可以执行类似的操作,但还需要考虑hte字段是否为null或空字符串

char comboLabel = ((string)formCombo.Rows[j]["Combo_Label"])[0];

首先将其转换为字符串 ,然后获取第一个字符...

char comboLabel = formCombo.Rows[j]["Combo_Label"].ToString()[0];

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