简体   繁体   中英

Convert varchar to char ? how to fix error

I get this error below when I want to convert DRMKOD to char ?

[ varchar(1) coloumn ] is the type of "DRMKOD" column on sql table.

String must be exactly one character long. at System.Convert.ToChar(String value, IFormatProvider provider) at System.String.System.IConvertible.ToChar(IFormatProvider provider) at System.Convert.ToChar(Object value)

 entity.DrmKod = Convert.ToChar(dt.Rows[i]["DRMKOD"]);

 public char DrmKod
        {
            get { return _DrmKod; }
            set { _DrmKod = value; }
        }

The two types are not compatible. varchar is a string, char is a single character.

Convert the result to a string, and then get the first character using str[0] (assuming the string even has any characters and is not null!).

What is the value that is dt.Rows[i]["DRMKOD"]? I can only think that it is something that is either empty or null.

VARCHAR(1) implies that it can be NULL or String.Empty.

if (dt.Rows[i].IsNull("DRMKOD") || (dt.Rows[i]["DRMKOD"] == String.Empty))
    entity.DrmKod = ' '
else
    entity.DrmKod = Convert.ToChar(dt.Rows[i]["DRMKOD"]);

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