mathgenius
mathgenius

Reputation: 513

An object reference is required for the non-static field, method, or property in a windows form

I know this error is extremely common. I have read on it and seen the other questions posed here, however I simply cannot figure out how to fix my particular problem.

I have a windows form with two comboboxes on it and other controls that are irrelevant to the case at hand. I have set up a method for when the first combobox changes and I want to change the list of items in the second one by some measure.

    private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox cb = sender as ComboBox;
        String Name = cb.Name;
        Name.Replace("Rank", "Target");
        cb = Form1.ControlCollection.Find(Name, false);
        for (int i = cb.SelectedIndex; i < Ranks.Count-1; i++)
        {

        }
    }

"Form1.ControlCollection.Find" raises the error in the title. Since I cannot make a new instance of Form1 (as I believe that will not reference my existing winform but make a new one?) and making the ComboBox_Selected... method static does not help at all, I don't know what to do.

I did try

Form1 frm = new Form1();
frm.ControlCollection.Find(Name, false);

and

this.ControlCollection.Find(Name, false);

but the error did not go away

Upvotes: 1

Views: 1137

Answers (1)

Steve
Steve

Reputation: 216293

If this code is part of the class Form1 then you should use the C# keyword this to refer to the current instance of the class.
Your code has also other problems that should be fixed in this way

private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    ComboBox cb = sender as ComboBox;
    String Name = cb.Name;

    // Strings are immutable so you need to reassign
    // the result of Replace to the same variable....
    Name = Name.Replace("Rank", "Target");

    // Find returns a Control array, you need to add some checking
    // Before using the control instance returned (if found)
    Control[] found = this.Controls.Find(Name, false);
    if(found.Length > 0)
    {
        cb = found[0] as ComboBox;
        if(cb != null)
        {
            for (int i = cb.SelectedIndex; i < Ranks.Count-1; i++)
            {
                ....
            }
        }
    }
}

Upvotes: 1

Related Questions