0

Hello
I need to group some Dropdown lists in ASP.NET form.So I wanted to create an array of DLs at the instance level as below in the code behind file.

DropDownList[] dls = { Dl1, Dl2, Dl3 };

where Dl1 etc are DropDown Lists on my form. So I get an error "A field initializer cannot reference a non static field method or property". However if I move the code inside a function it works OK. But I need to create it at instance level so multiple methods can use it.

Any Ideas about the best way to handle this.

1
  • 1
    Put it in the constructor..... Commented May 5, 2011 at 1:34

2 Answers 2

3
class MyPage : Page {

    DropDownList[] dls;

    protected void Page_Init(object sender, EventArgs e)
    {
        dls = new []{ Dl1, Dl2, Dl3 };
    }
    ...

}
Sign up to request clarification or add additional context in comments.

4 Comments

Yours is the long form syntax, but josephj1989's is the same thing.
Your second version is an intermediately short syntax - the question author is using the shortest possible c# syntax. (Oops, fyi - this is in response to the deleted comment)
@John ya I realized that. The other thing was that I didn't read the question fully. I have edited the answer now.
+1 (voted changed) BTW, I prefer using the ASP.NET event handlers too, instead of ctor, for control-related stuff.
0

This is the only way I could get it to work. Credit to slugster for the idea:

public partial class _Default : System.Web.UI.Page
{
    DropDownList[] dls = null;

    public _Default()
    { 
        dls = new DropDownList[] { dl1, dl2, dl3 };
    }

    protected void Page_Load(object sender, EventArgs e)
    {            
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.