2014-12-25 34 views
-1

嗨,我使用下面的代码来显示按钮。如果查询不返回任何数据

如果查询结果为“0”的知名度真WORKING

如果查询发现,在数据库中的知名度没有数据错误。 NOT WORKING

string insertSql = "SELECT Status from User_friend WHERE (ProfileId1 = 
       @FriendProfileId) AND (ProfileId = (SELECT ProfileId FROM User_Profile 
       WHERE UserId = @UserId))"; 

     using (SqlConnection myConnection = new SqlConnection(connectionString)) 
     { 


      myConnection.Open(); 
      SqlCommand myCommand = new SqlCommand(insertSql, myConnection); 
      myCommand.Parameters.AddWithValue("@FriendProfileId", 
          Request.QueryString["ProfileId"]); 
      myCommand.Parameters.AddWithValue("@UserId", currentUserId); 
      if (myCommand.ExecuteScalar().ToString() == null) 
      { 
       friendRequestSent.Visible = false; 
       addFriend.Visible = true; 

      } 
      else if (myCommand.ExecuteScalar().ToString() == "0") 
      { 
       friendRequestSent.Visible = true; 
       addFriend.Visible = false; 

      } 
     } 
+2

你得到'NullReferenceException',对不对? –

+1

您正在调用'ExecuteScalar'两次。存储一次这个值,然后运行你的逻辑。 –

+0

嗨马修,谢谢。我是新来的ASP.NET和真正不明白如何存储值 –

回答

1

对于NULL值,ExecuteScalar将具有值DBNull.Value。您还应该考虑执行查询一个,将结果保存在一个对象变量中,然后使用它两次。

object result = myCommand.ExecuteScalar(); 
if (result == DBNull.Value) 
{ 
    friendRequestSent.Visible = false; 
    addFriend.Visible = true; 
} 
else if (Convert.ToString(result) == "0") 
{ 
    friendRequestSent.Visible = true; 
    addFriend.Visible = false; 
} 
+0

谢谢,现在我得到一个错误的其他如果(myCommand.ExecuteScalar()。ToString()==“0”) { friendRequestSent.Visible = true; addFriend.Visible = false; } –

+0

我编辑了我的回复,以包含一次执行查询的建议。 –

0

拳头我想知道null是什么意思。不应该是Null

if (myCommand.ExecuteScalar().ToString() == "Null") 

或者,如果它意味着它不存在,你可以留下空:

if (myCommand.ExecuteScalar().ToString() == "") 
+0

null表示该行在数据库中不存在 –