Reputation: 5264
The form1 has three comboboxes. In the form I tried to create the below code.
public partial class Form1 : Form
{
private List<ComboBox> comboBoxes = new List<ComboBox>()
{
combobox1,combobox2,combobox3
};
}
I am getting the error like
A field initializer cannot reference the non-static field, method, or property
But I can access these comboxes inside the function. I want to create the list of comboboxes. Tell me why I couldn't access it, and How to achieve this?
Upvotes: 0
Views: 291
Reputation: 34421
You need to add the controls in a method
public List<ComboBox> comboBoxes = new List<ComboBox>()
public Form1()
{
InitializeComponent();
comboBoxes.AddRange(new ComboBox[] {comboBox1, comboBox2, comboBox3});
}
Upvotes: 1
Reputation: 24903
Compiler Error CS0236: Instance fields cannot be used to initialize other instance fields outside a method.
You can initialize list in constructor after initializing controls:
public partial class Form1 : Form
{
public Form1()
{
//...
comboBoxes = new List<ComboBox>() { combobox1,combobox2,combobox3 };
}
}
Upvotes: 1