Search code examples
c#hiddenfield

C# field initializer error when using a hidden field variable


I'm very new to C#, so there's probably a very simple answer to this, it's just my noobness that's stopping me getting it.

I'm trying to extract a parameters value from a URL, and then pass it to a query string in code behind.

I've no problem getting the parameter value and pass it to a hiddenfield (that's being done in jQuery/HTML on the .aspx page), however when I try to use it's value 'URLVariable' in the code behind I consistently get 'A field initializer cannot reference the non-static field, method, or property 'P1'' error

Making P1 static makes the error go away, but means that the value doesn't change when the page is reloaded, and that's really the problem I'm trying to solve. I'm pretty sure this is me failing to do constructors properly, but I can't see what I'm getting wrong.

Thanks for any help in advance, code is below.

public partial class SqlDat : System.Web.UI.Page
{
public string P1;

public SqlDat()
{ (new SqlDat()).P1 = URLVariable.ToString(); }

public string tb1text = "SELECT Stuff FROM Somewhere WHERE Something= "+SqlDat.P1;//+ HttpUtility.ParseQueryString(BaseUrl.Query).Get("Tim");

}

Solution

  • I'm guessing your class looks like this:

    public class SqlDat
    {
        public string P1;
    
        public SqlDat()
        {
            P1 = URLVariable.ToString();
        }
    
        public string tb1text = "SELECT Stuff FROM Somewhere WHERE Something = "+SqlDat.P1;//+ HttpUtility.ParseQueryString(BaseUrl.Query).Get("Tim");
    }
    

    That won't work. First and foremost not because SqlDat.P1 refers to a static member on the type SqlDat, which P1 isn't, so you're looking for this.P1 or simply P1.

    If you want to refer to other members in an initializer, and especially after said member is initialized in the constructor, then you need to set it in the constructor:

    public class SqlDat
    {
        public string P1 { get; set; }
        public string tb1text { get; set; 
    
        public SqlDat()
        {
            P1 = URLVariable.ToString();
            tb1text = "SELECT Stuff FROM Somewhere WHERE Something = " + P1;
        }
    }
    

    Then you can let P1 and tb1text be properties too ({ get; set; }).

    You also may want to reconsider your naming, and whether to manually craft SQL strings (read about SQL injection), using an ORM instead of querying the database yourself and not using statics (where does URLVariable come from?).