简体   繁体   中英

Query Won't Work in ASP.net

I am trying to hide this button if the query result is = to btn1.CommandArgument.

The query works, because I have tested it, but the whole solution is not work.

If I replace

myCommand.ExecuteScalar().ToString() 

in the if statement to the query result, the button is hidden.

I have looked several times, but can't find any problems. Thank you.

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;
        }
    }
}

You need to execute the .ExecuteScalar() call only once ! Grab the result (of type object ) and then check to make sure it's not null and if it is, call .ToString() on it and compare to the other string you want to check against:

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM