Ibrahim Shaikh Ibrahim Shaikh - 2 months ago 14
C# Question

object cannot be cast from DBNULL to other types model mvc5

I am creating a web app with mvc5 i have multiple users in my database
for eg

USERS

user1) username=ibrahim Password=1ibrahim
user2) username=admin password=4321

when i am logging in from user 1(ibrahim) the page is successfully redirecting to welcome page,
but when i am logging in from user to(admin) the error is coming


An exception of type 'System.InvalidCastException' occurred in
mscorlib.dll but was not handled in user code

Additional information: Object cannot be cast from DBNull to other
types.


on
user = Convert.ToBoolean(cmd.ExecuteScalar());
this line

here is my code

public class loginuser
{
SqlCommand cmd;
public string role { get; set; }
public string username { get; set; }
public string password { get; set; }
public bool getlogintype(string role, string username, string password)
{

string tru = "";
string fals = "";
bool user;
string strname = "";
SqlConnection con = new SqlConnection("Data Source=erp.hti-india.com,1434;Initial Catalog=erp;Connect Timeout=3600;User Id=erprakesh;Password=14erprakesh14");
List<object> login = new List<object>();
if (role == "Admin" || role == "Super Admin" || role !=null)
{
cmd = new SqlCommand("select * from [admin] where userid='" + username + "' and pass ='" + password + "'", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
user = true;
//HttpContext.Current.Session["userid"] = username.ToString();
//HttpContext.Current.Session["tru"] = tru.ToString();
// want to redirect to welcome page if condition satisfied.
}
else
{
user = false;
//want to show the label error message(declare as string errormsg)
}
con.Close();
}
con.Open();
user = Convert.ToBoolean(cmd.ExecuteScalar());
con.Close();
return user;
}
}

Answer

Your query returns null, represented by DBNull.Value. You should check on that before converting to a boolean:

object result = cmd.ExecuteScalar();
if (result == DBNull.Value)
{
    user = false; // or something like that
}
else
{
    user = Convert.ToBoolean(result);
}

Be aware that your statement is vulnerable for SQL injection. Always use parameterized queries! Also be careful with your select *. If you add columns you might end up in problems. Only select the field you require.