views:

29

answers:

1

Hello,

I have the following code in my aspx code-behind and it works fine. Because I am going to use it on more than one page, I'd like to move it to a class file. I am not sure how to do this properly.

#region autocomplete search

[WebMethodAttribute(), ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
    SqlConnection con;
    SqlCommand cmd;
    string cmdString = "SELECT TOP(15) Title FROM posts WHERE (Title LIKE '%" + prefixText + "%') OR (Content LIKE '%" + prefixText + "%')";
    con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbMyCMSConnectionString"].ConnectionString);

    cmd = new SqlCommand(cmdString, con);
    con.Open();

    SqlDataReader myReader;
    List<string> returnData = new List<string>();

    myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

    while (myReader.Read())
    {
        returnData.Add(myReader["Title"].ToString());
    }

    myReader.Close();
    con.Close();

    return returnData.ToArray();
}

#endregion

I tried calling it from the code-behind page like this:

BlogFrontUtil.GetCompletionList(prefixText, count, contextKey);

...but it's not working, I get the red squiggly lines. The error message says that it is a method but used like a type.

Could some one please teach me how this is done properly. I have limited experience.

Thank you

+1  A: 

In your new class add the method:

public static class NewClass
{
    public static string[] GetCompletionList(string prefixText, int count, string contextKey)
    {
        SqlConnection con;
        SqlCommand cmd;
        string cmdString = "SELECT TOP(15) Title FROM posts WHERE (Title LIKE '%" + prefixText + "%') OR (Content LIKE '%" + prefixText + "%')";
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbMyCMSConnectionString"].ConnectionString);

        cmd = new SqlCommand(cmdString, con);
        con.Open();

        SqlDataReader myReader;
        List<string> returnData = new List<string>();

        myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

        while (myReader.Read())
        {
            returnData.Add(myReader["Title"].ToString());
        }

        myReader.Close();
        con.Close();

        return returnData.ToArray();
    }
}

Then in your service call that method:

[WebMethodAttribute(), ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
    string[] s = NewClass.GetCompletionList(prefixText, count, contectKey);
    return s;
}
Dustin Laine
Dustin, Thank you! Now I understand the mistake I made. Also, thank you for understanding my question and providing a simple answer that I was looking for.
Scott W.
No worries, glad it helped.
Dustin Laine