Jaco
Jaco

Reputation: 17

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

Upvotes: 1

Views: 52

Answers (1)

marc_s
marc_s

Reputation: 755321

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

Upvotes: 1

Related Questions