简体   繁体   中英

ASP.NET declaring array of Controls in CodeBehind not working

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.

class MyPage : Page {

    DropDownList[] dls;

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

}

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)
    {            
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM