0

//in main form there is a public listbox "lstMain"

//in addTask form

Main main = new Main();

private void btnTaskAdd_Click(object sender, EventArgs e)
{
    main.lstMain.Items.Add(lstAddTask.SelectedItem.ToString());
    this.Close();
}

this code doesnt pass the selected item in lstAddTask to lstMain in the main form

any help would be great thanks :-)

Sid M
  • 4,354
  • 4
  • 30
  • 50
  • possible duplicate of [How can I update a label on one form from another form in C#?](http://stackoverflow.com/questions/4533547/how-can-i-update-a-label-on-one-form-from-another-form-in-c) – Eugene Podskal Jul 29 '14 at 14:55

2 Answers2

0

you should use the following:

// this function should be written in the main form
private void btnTaskAdd_Click(object sender, EventArgs e)
{
    var form=new addTaskForm();
    if(form.ShowDialog()==DialogResult.Ok)
    {
         // in the form addTaskForm you add a string property called SelectedItem, 
         // and on selection change in the lstAddTask then you set the SelectedItem, 
         // the lstAddTask_SelectedIndexChanged will be written in addTaskForm
         lstMain.Items.Add(form.SelectedItem);
         this.Close();
    }
}

hope this will help you

regards

Monah
  • 6,714
  • 6
  • 22
  • 52
0

Your code isn't working because you don't have a reference to the first form in the second form.

You could use Hadi's answer, or modify your second form to have a property where you can store a reference to the first form.

For example, Main MainForm {get;set;}

private void btnTaskAdd_Click(object sender, EventArgs e)
{
    main.lstMain.Items.Add(lstAddTask.SelectedItem.ToString());
    this.Close();
}

And then in your main form

var form = new addTaskForm();
form.MainForm = this;
form.ShowDialog()
//etc.
Spivonious
  • 718
  • 7
  • 20