This is incorrect, even in the form1
constructor which should contain the method call with ()
:
//form2
private void button1_Click(object sender, EventArgs e)
{
form1 limpar = new form1(); // em vez de form1;
limpar.limparListBox();
}
What you do here is to call the limparListBox()
method of a form1
object instance that has just been created and is probably not the instance that is already being displayed on the screen and must have been created at another time.
Another detail refers to the lack of default for classes and members names when using CamelCase (or lowerCamelCase >) which is the default used in Java but not in C #, which uses PascalCase (or UpperCamelCase ). I will assume that the types were created with Visual Studio and the case pattern in the class names was retained.
So assuming we have two forms ( Form1
and Form2
) and that Form2
is opened with a button on Form1
. The code looks like this:
//Form1
private void button1_Click(object sender, EventArgs e)
{
var form2 = new Form2();
form2.Form1 = this; //aqui, vamos criar uma propriedade no Form2 que recebe a referência do Form1: this
form2.Show();
}
public void LimparListBox() //aqui o método que será chamado no Form2 setado como public
{
//
}
And the code for Form2:
//Form2
public partial class Form2 : Form
{
public Form1 Form1 { get; set; } //essa é a propriedade que recebe a referência this do Form1
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// form1 limpar = new form1();
// em vez de criar uma nova instância ...
Form1.LimparListBox(); //... usamos aquela passada por referencia
}
}