Search code examples
c#visual-studio-2010sharepoint-2010web-parts

How to fix variable does not exist in current context in SharePoint WebPart code behind?


I am a complete noob when it comes to developing webparts for SharePoint 2010. I have created a webpart that has button on it. When that button is clicked, I would like it to redirect the user to another page. That would seem like an easy operation to do but I have run into roadblocks.

In my MyWebPart.ascx.cs file, I have the following bit of code:

protected void Button_Click(object sender, EventArgs e)
    {
        // Get the values the user inputted
        try
        {
            String category = SearchBySelector.SelectedValue;
            String keyword = SearchField.Text;
            SPWeb root = SPContext.Current.RootWeb.Url;
            String url = root + "/path/to/site.aspx?category=" + category + "&keyword=" + keyword;
            SPUtility.Redirect(url);
        }
        catch (Exception ex)
        {
            StatusLabel.ForeColor = "#FF0000";
            StatusLabel.Text = "Exception encountered." + ex.Message;
        }
    }

The problem I am having is that SPContext (and SPUtility) is not being recognized in this context. How do I fix this? I assume I need some sort of include somewhere? I am not a C# expert either which is probably evident by my code.

Any help would be appreciated.


Solution

  • You'll need the fully qualified namespaces for both SPContext and SPUtility, which are Microsoft.SharePoint.SPContext and Microsoft.SharePoint.Utilities.SPUtility respectively.

    You can either use those fully qualified class names in your code, or tack two using statements onto the top of your code file:

    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Utilities;
    

    If Visual Studio still barks at you about not recognizing these types or namespaces, you'll want to be sure the Microsoft.SharePoint assembly is added to the references in your project. You can add references from the Solution Explorer window in Visual Studio.