我正在尝试将 If 语句用于两个查询。如果查询 1 = 查询 2
string select = "Select ProfileId from Project_list Where ProjectId = @ProjectId";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(select, myConnection);
myCommand.Parameters.AddWithValue("@ProjectId", querystring);
object Project_listResult = myCommand.ExecuteScalar();
}
string getProfileId = "SELECT ProfileId FROM User_Profile WHERE UserId = (@UserId)";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(getProfileId, myConnection);
myCommand.Parameters.AddWithValue("@UserId", currentUserId);
object User_profileResult= myCommand.ExecuteScalar();
}
if (Project_listResult == User_profileResult)
{
addFollowerButton.Visible = true;
}
这是我拥有的代码,但不起作用。
错误 18 名称"Project_listResult"在当前
错误 19 名称"User_profileResult"在当前
您必须在外部定义这两个值,以便使用它们的范围。现在你在使用中定义了这两个值,所以这些值只是在 only under 的范围内,在 THAT 之外不可用,所以你得到这个错误。
一个简单的建议是避免使用属于不同语言的关键字,因为您使用 select 作为变量名称。这有助于提高可读性并增加混乱。
指
object Project_listResult = null;
object User_profileResult = null;
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(select, myConnection);
myCommand.Parameters.AddWithValue("@ProjectId", querystring);
Project_listResult = myCommand.ExecuteScalar();
}
string getProfileId = "SELECT ProfileId FROM User_Profile WHERE UserId = (@UserId)";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(getProfileId, myConnection);
myCommand.Parameters.AddWithValue("@UserId", currentUserId);
User_profileResult= myCommand.ExecuteScalar();
}
if (Project_listResult.Equals(User_profileResult))
{
addFollowerButton.Visible = true;
}
如果我理解你,你正在尝试比较对象。所以你必须尝试
if (Project_listResult.Equals(User_profileResult))
addFollowerButton.Visible = true;
http://msdn.microsoft.com/en-us/library/bsc2ak47(v=vs.110).aspx