Search code examples
c#functionlistviewlistviewitem

Can't add ListViewItem in function


I wrote a code that is build from 2 forms, the main form - (Form1) that gets 3 strings from the sub form (AddTask)

In the main form:

public partial class Form1 : Form
{
    int count = 0;
    string taskName2, DateTime2, More2;
    public Form1(string taskName1, string DateTime1, string More1, bool startworking)
    {
        InitializeComponent();

        taskName2 = taskName1;
        DateTime2 = DateTime1;
        More2 = More1;
        if(startworking)
        {
            StartWorking();
        }
    }

You can see I create 3 string to global use, Form1 gets 3 strings and 1 boolean variable. When the boolean is true the function StartWorking start.

In the sub form I have a button and 3 text boxes. The button has a click event:

string taskName1 = textBox1.Text;
string DateTime1 = textBox2.Text;
string More1 = textBox3.Text;
Form celender = new Form1(taskName1, DateTime1, More1, true);
this.Close();

So when I press the button on the sub form the boolean is set to true and the StartWorking function starts.

Up to here all is alright.

The function StartWorking:

public void StartWorking()
{
    MessageBox.Show(taskName2 + "  " + DateTime2 + "  " + More2);

    ListViewItem lvi = new ListViewItem(taskName2);
    lvi.SubItems.Add(DateTime2);
    lvi.SubItems.Add(More2);
    listView1.Items.Add(lvi);    
}

Now in the function the MessageBox works and shows the strings, but when I see the listview1 nothing changes. Why doesn't it create anything?


Solution

  • You didn't show Form1 after instantiating it. Show the Form1 with Show() method celender.Show(); and also change your code like this:

    Hide();
    string taskName1 = textBox1.Text;
    string DateTime1 = textBox2.Text;
    string More1 = textBox3.Text;
    Form1 celender = new Form1(taskName1,DateTime1,More1,true);         
    celender.Show();
    celender.Closed += (s, args) => this.Close();