Method does not work when called

1

I have two forms:

No form1 is a ListBox with some pre-inserted data and a method. In form2 there is a button that executes a method in form1 .

//form1
public void limparListBox()
{
    listBox1.Items.Clear();
}

//form2
private void button1_Click(object sender, EventArgs e)
{
    form1 limpar = new form1;
    limpar.limparListBox();
}

For some reason I do not know, it just does not clean% w /%.

I want to know the reason and how I can solve this problem.

    
asked by anonymous 22.03.2014 / 04:05

2 answers

1

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
    }
}
    
22.03.2014 / 15:29
0

I have no experience with C #, but from what I understand the following should work:

Assuming they are in separate namespaces , add the namespace of Form1 in using of Form2:

using Form1;

If they happen to be in the same namespace , the above step is not necessary.

And call the public variable form1 like this:

private void button1_Click(object sender, EventArgs e)
{
    form1.limpar.limparListBox();
}
    
22.03.2014 / 04:45