-4

I have 2 forms, let's call them form1 and form2. Inside form1 i have created a method that connects to an access database, and also inserts the values from the database into a combobox. My question is : how do i call my method which is inside my form1, for a combobox inside form2? The error that i get says The name "MyComboBoxName" does not exist in the current context.

I have tried to use inheritence between my 2 classes, but then i get 2 of the same comboboxes.

  • How do you call any method in a class that's different to the one you're currently in? Microsoft made string class, and made ToUpper() method; you can't inherit string but you can still make a string and call it's ToUpper method.. – Caius Jard Dec 26 '21 at 16:16
  • Your question tags are off, and your question lacks the code that shows how are you trying to access the combobox. But ultimately it is [very likely already answered](https://stackoverflow.com/search?q=%5Bc%23%5D+access+control+from+another+form) and you should have searched a bit stronger. Check that search and I hope it helps you. – Cleptus Dec 26 '21 at 16:16
  • There are *hundreds* of posts here showing how to call a method from a different class. Note that the title and the body of the post ask 2 different questions... – Ňɏssa Pøngjǣrdenlarp Dec 26 '21 at 16:20
  • Does this answer your question? [Best way to access a control on another form in Windows Forms?](https://stackoverflow.com/questions/8566/best-way-to-access-a-control-on-another-form-in-windows-forms) – Bill Tür stands with Ukraine Dec 26 '21 at 18:59
  • Please provide enough code so others can better understand or reproduce the problem. – Community Jan 04 '22 at 14:10

1 Answers1

-1

The easiest solution is to define your method statically in the first form:

public partial class Form1 : Form
{
    public static void CustomMethod()
    {
        //Your codes
    }
    public Form1()
    {
        InitializeComponent();
    }
}

Then call it from the second form:

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Form1.CustomMethod();
    }
}
R_J
  • 52
  • 12