2

I have two classes(forms), and I would like an item from class2 to be added to listBox in class1 when I click "Accept" button.

I tried with the following code, but nothing changes in the listBox:

private void button1_Click(object sender, EventArgs e)
{
    CarRental i = new CarRental();
    string id = idRental.Text.ToString();

    i.listBox1.Items.Add(id);
    i.listBox1.Update();
    this.Close();
}

Where did I make the mistake?

0

3 Answers 3

2

Declare RentalId property on Form2. And at CarRental form (your first form) do following:

using(Form2 form2 = new Form2())
{
    if (fomr2.ShowDialog() != DialogResult.OK)
        return;

    listBox.Items.Add(form2.RentalId);
}

Implement Fomr2.RentalId property this way:

public string RentalId
{
   get { return idRental.Text; } // you don't need ToString() call
}

Then select your "Accept" button and set its DialogResult property to OK. Thus clicking on that button will close your dialog form and return DialogResult.OK.

Sign up to request clarification or add additional context in comments.

2 Comments

Where excatly in form1 do i put that using{...}?
@cvenko this using shows Form2, so put it where you need to show Form2
0

you created a new entity of type CarRental. what you should do is to send the first form to the second on construct, and modify things through that instance.

Comments

0

You need to access the open form instead of creating new instance of CarRental form

private void button1_Click(object sender, EventArgs e)
{
    CarRental i = (CarRental)Application.OpenForms["CarRentalFormObjectName"];
    string id = idRental.Text.ToString();

    i.listBox1.Items.Add(id);
    i.listBox1.Update();
    this.Close();
}

2 Comments

shouldn't you pick just the first? or at least one?
What excatly do I need to put in ["CarRentalFormObjectName"]?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.