-3

I am new to c# and I am writing a simple application that want to pass Form 1 listview value to the Form 2 textbox. So how can I pass these subitem to the Form 2 textboxes?

 private void Form1_Load(object sender, EventArgs e)
        {
            ListViewItem item = new ListViewItem("ITEM1");
            item.SubItems.Add("ITEM2");
            item.SubItems.Add("ITEM3");
            listView1.Items.AddRange(new ListViewItem[] { item });
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 newForm = new Form2();
            newForm.Show();
        }
Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
  • 1
    See my two form project on following webpage. You need to call a method in Form2 that take an input from form1. http://stackoverflow.com/questions/37366447/keep-checked-radio-button-checked-through-forms-c-sharp-visual-studio-2010/37366641#37366641 – jdweng May 21 '16 at 20:04
  • OH NO! NOT AGAIN! The most asked question on Stack Overflow returns again. – Uwe Keim May 21 '16 at 20:19
  • Important note to people answering these questions: when a person types this title they will see several links to near-identical questions, with the answers already given, in the Stack Overflow UI before the Submit button. To click Submit they had to have ignored all the previous answers. If your answer is no different from any of the previous answers, what makes you think the questioner won't ignore your answer as well? – Dour High Arch May 21 '16 at 20:29

2 Answers2

1

To do this you need to declare property in your Form2 class:

public class Form2
{
    public ListViewItem[] Items{get;set;}

    //your code
}

then you can pass listView1.Items to form2:

private void button1_Click(object sender, EventArgs e)
{
    Form2 newForm = new Form2();
    newForm.Items = listView1.Items; // pass items to form2
    newForm.Show();
}

and then in form2 load event handler get necessary values and set it to textboxes of form2:

public class Form2
{
    public ListViewItem[] Items{get;set;}

    private void Form2_Load(object sender, EventArgs e)
    {
        textBox1.Text = Items[0].SubItems[0].Text; // or your logic here in this handler            
    }

    //your code
}
Roman
  • 11,966
  • 10
  • 38
  • 47
1

You can modify Form2's constructor like this

public partial class Form2 : Form
{
    public Form2(ListViewItem item)
    {
        InitializeComponent();
        textBox1.Text = item.Text;   // item.Subitems[index].Text if you want the value of subitems
    }
}

And when you create your form, you pass in the item like so

private void createNewForm()
{
    Form2 f = new Form2(listView1.Items[0]); // to pass the first item in this case
    f.Show();
}
Gabriel Em
  • 133
  • 7