0

I have 2 forms. Form 1 which shows a ListView and Form 2 a button called button1. What I'm trying to do is when the button on form 2 is clicked. I want it to fill the Listview on form1.

The listview has 3 columns; Flavour Quantity Sub-Total

When the button1 is pressed, it should show Vanilla, 1, £1.00 in the listview on form1.

I'm able to do this if the listview is on the same form as the button, but not if it's on different forms.

Form1

public partial class form1: Form
{
    public form1()
    {
        InitializeComponent();
    }

Form2

public partial class form2: Form
{
    public form2()
    {
        InitializeComponent();
    }

private void button1_Click(object sender, EventArgs e)
    {
        ListViewItem lvi = new ListViewItem("Vanilla");
        lvi.SubItems.Add("1");
        lvi.SubItems.Add("£1.00");
        listView1.Items.Add(lvi);
    }
AnotherUser
  • 139
  • 1
  • 2
  • 15

1 Answers1

1

Create a reference of form1 in form2 like this:

class Program {
    static void Main() { 
        var form1 = new Form1();
        var form2 = new Form2(form1);
    }
}

public partial class Form1: Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void DoStuff(ListViewItem lvi) {
        // TODO: Stuff
    }
}

public partial class Form2: Form
{
    private Form1 _form1;

    public form2(Form1 form1)
    {
        InitializeComponent();
        _form1 = form1;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ListViewItem lvi = new ListViewItem("Vanilla");
        lvi.SubItems.Add("1");
        lvi.SubItems.Add("£1.00");
        listView1.Items.Add(lvi);

        _form1.DoStuff(lvi);
    }
}
Duncan Lukkenaer
  • 12,050
  • 13
  • 64
  • 97