I am building a small windows form application in C#. Within the form code I define a public struct with a ToString method that must build part of its output from items in comboBoxes on the same form. This doesn’t sound like it should be difficult
public partial class Form1 : Form
{
public struct OrderLineItem
{
string someString;
int index;
string ToString()
{return someString + ActiveForm.sizeComboBox.Items[index].ToString();}
}
}
It complains that it cannot find a definition for sizeComboBox. If I explicitly use the name of the form, it says an object reference is required for the static field…
I’m not quite sure what it means by that. Using this.sizeComboBox refers to the struct, not the form. Using just sizeComboBox, again, an object reference is required.
The struct knows about its containing class type, but it doesn’t know about any particular instance of that type, unless you tell it. For example, you can create a constructor that takes a Form1 object, and it can save a reference to that form in a member variable.
That said, this is a seriously questionable design.
The tiered structure of this application appears to be upside-down. The order-line-item objects should exist at a lower level than the user interface layer. The UI can sometimes see the business objects (order, order-line-item, etc.), but the business objects should not know anything about the UI.
If you can invert this structure, it will make the code much cleaner.