[InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.] [duplicate]

瘦欲@ 提交于 2020-01-06 02:50:08

问题


The error line:

Source Error:

Line 37:         while (rdr.Read()==true)
Line 38:         {
Line 39:             if (TextBoxUserName.Text == (string)rdr["CUserName"]) 
Line 40:             {
Line 41:                 ClientScript.RegisterStartupScript(csType,"Error",scriptErrorUserId);

It pops up when I tried to register an account.

I use microsoft access as database.

Database - CUserName Session - sUserName and there's @eUserName

any idea guys?


回答1:


Replace this

if (TextBoxUserName.Text == (string)rdr["CUserName"])

with

if (TextBoxUserName.Text == rdr["CUserName"].ToString())



回答2:


You need to check if rdr["CUserName"] equals to System.DBNull.Value first before converting it to string. Change this:

if (TextBoxUserName.Text == (string)rdr["CUserName"])

to this:

string userName = rdr["CUserName"] != System.DBNull.Value ? (string)rdr["CUserName"] : string.Empty;
if (TextBoxUserName.Text == userName)


来源:https://stackoverflow.com/questions/21216641/invalidcastexception-unable-to-cast-object-of-type-system-dbnull-to-type-sy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!