开发者

Question about "bit" datatype

开发者 https://www.devze.com 2023-03-19 22:11 出处:网络
public static bool CheckIfUserISbanned(Guid guid) { StringBuilder sb = new StringBuilder(); sb.Append(\"SELECT Banned\");
    public static bool CheckIfUserISbanned(Guid guid)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("SELECT Banned");
    sb.Append(" FROM dbo.Users");
    sb.Append(" WHERE UsersID=@UserID");
    object o;
    bool isBanned = false;
    string myConnectionString = AllQuestionsPresented.connectionString;
    using (SqlConnection conn = new SqlConnection(AllQuestionsPresented.connectionString))
  开发者_运维知识库  {
        SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
        conn.Open();
        cmd.Parameters.Add("@UserID", SqlDbType.UniqueIdentifier).Value = guid;
        o = cmd.ExecuteScalar();
    }

    isBanned = o == null ? false : true;//Problem here
    return isBanned;
}

The problem is that the object receives always a value which is not null. But in the Users table at the Banned field, I set its type to "Allow Nulls"... I can see that there are nulls, but no null is retreived..Something else does.. which makes the "isBanned" parameter be true..the whole time.. Why is it happening, and how can I know when the the object is bool True.


If your database query returns NULL in SQL, this gets converted to DBNull in .NET. So rather than testing for null, test for DBNull.Value.


You should test for DBNull.Value in your expression


try this:

isBanned = o == null ? false : true;

also check if the string is empty or not by using string.Empty:

isBanned = o == string.Empty ? false : true;
0

精彩评论

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