-1

I'm trying to change the SelectedIndex of a list box in another form, but I come across the above mentioned error. Looking at the causes of this error in other posts they seem to be from having a static method in the target form, but I can't figure out in my code where this is happening.

Main form:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Assignment_1
{
    public partial class frmMain : Form
    {

        public frmMain()
        {
            InitializeComponent();
        }

            public void setListIndex(int index)
        {
            lstEvents.SelectedIndex = index;
        }
    }
}

Second Form

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Assignment_1
{
    public partial class frmSearch : Form
    {
        private int selectedEvent;

        public frmSearch(int index)
        {
            InitializeComponent();
            selectedEvent = index;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            frmMain.setListIndex(selectedEvent); //error here
        }
    }
}

Any thoughts? If there another way to change the selected item in another form?

Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135

1 Answers1

0

When you call frmMain.setListIndex(selectedEvent); you're attempting to call a class (static) method; however, the method isn't static. Static methods are part of the classes (like static void Main(String[])). Non-static methods, or methods missing the modifier static, require an object reference, either built by new or a retrieval method.

So, we can see you have two options: make the method static, or create an object. To me, since we're talking forms, creating the object is the best solution.

Inside the btnSearch_Click method:

{
    frmMain f = new frmMain();
    f.setListIndex(selectedEvent);
}
D. Ben Knoble
  • 4,273
  • 1
  • 20
  • 38