查询在 ASP.net 中不起作用

Query Won't Work in ASP.net

如果查询结果为 = 到 btn1.CommandArgument,我试图隐藏此按钮。

查询有效,因为我已经对其进行了测试,但整个解决方案均无效。

如果我替换

myCommand.ExecuteScalar().ToString() 

在查询结果的if语句中,按钮是隐藏的。

我看了好几遍,没发现什么问题。谢谢。

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    Button btn1 = (Button)e.Item.FindControl("addFollowerButton");

    // request Query string
    var querystring = Request.QueryString["ProjectId"];

    string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

    string select = "Select ProfileId from Project_Follower Where ProjectId = @ProjectId";

    using (SqlConnection myConnection = new SqlConnection(connectionString))
    {
        myConnection.Open();

        SqlCommand myCommand = new SqlCommand(select, myConnection);
        myCommand.Parameters.AddWithValue("@ProjectId", querystring);

        myCommand.ExecuteScalar();

        if (myCommand.ExecuteScalar().ToString() == btn1.CommandArgument.ToString())
        {
            Button hdn = (Button)e.Item.FindControl("addFollowerButton");
            btn1.Visible = false;
        }
    }
}

您只需要执行.ExecuteScalar()调用一次!获取结果(object 类型),然后检查以确保它不是 null,如果是,则对其调用 .ToString() 并与您要检查的其他字符串进行比较:

using (SqlConnection myConnection = new SqlConnection(connectionString))
{
    myConnection.Open();

    SqlCommand myCommand = new SqlCommand(select, myConnection);
    myCommand.Parameters.AddWithValue("@ProjectId", querystring);

    object result = myCommand.ExecuteScalar();

    if (result != null && result.ToString().Equals(btn1.CommandArgument.ToString()))
    {
        Button hdn = (Button)e.Item.FindControl("addFollowerButton");
        btn1.Visible = false;
    }
}