locked
How do I resolve ExecuteScalar issue? RRS feed

  • Question

  • User-218090889 posted

    Hi Friends,

    First, I want to appreciate you guys that responded to my last post. Thank you all.

    Now, still in the same project I am doing,
    I have set of code to handle event for GridView databound.
    I want to get an Id (UserId) from database which is placed on a textbox (Id =UserIdTextBox), then use the value of the textbox to make a select count in the database, get the count value and use it for other purpose. I connect to my database using database class on a separate class file. Below is my code in code behind:

     protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            Int32 UserFriendId = 0;

     if (e.Row.RowType == DataControlRowType.DataRow)
            {

     TextBox UserID = (TextBox)(e.Row.FindControl("UserIdTextBox"));
                string UserId = UserID.Text;

     string getUserFriendId = "SELECT COUNT(*) FROM TableName WHERE (UserfriendId = '"  +UserId + "')";

    DataSet ds = new DataSet();
                SqlCommand cmd = new SqlCommand();

         ds = dbClass.ConnectDataBaseReturnDS(getUserFriendId);

        UserFriendId = ((Int32)cmd.ExecuteScalar());

    }

    /// This is my Database class

     public DataSet ConnectDataBaseReturnDS(string Query)
            {
                ds = new DataSet();
                con = new SqlConnection(@"Data Source=MyName;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");
                cmd.CommandText = Query;
                cmd.Connection = con;
                da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Open();
                cmd.ExecuteNonQuery();
                cmd.ExecuteScalar();
                con.Close();
                return ds;
            }

    But when I try to run the code I error as below:

    Exception Details: System.InvalidOperationException: ExecuteScalar: Connection property has not been initialized.

    So How do I go about that.

    Monday, August 22, 2016 3:17 PM

Answers

  • User1577371250 posted

    Hi,

    You need to Write a seperate method for the ExecuteScalar().

    public object ExecuteDBScalar(string Query)
            {
                ds = new DataSet();
                con = new SqlConnection(@"Data Source=MyName;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");
                cmd.CommandText = Query;
                cmd.Connection = con;
               
                con.Open();
    
              object result =  cmd.ExecuteScalar();
                con.Close();
                return result;
            }
    object res = dbClass.ExecuteDBScalar(getUserFriendId);
    
    int scalarValue = (Int32)res;



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 23, 2016 6:35 AM

All replies