如何将Form 1 listview值传递给Form 2文本框?

时间:2016-05-21 19:54:30

标签: c# winforms

我是c#的新手,我正在编写一个简单的应用程序,希望将Form 1 listview值传递给Form 2文本框。那么如何将这些子项传递给Form 2文本框?

 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();
        }

2 个答案:

答案 0 :(得分:1)

为此,您需要在Form2类中声明属性:

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

    //your code
}

然后你可以将listView1.Items传递给form2:

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

然后在form2中加载事件处理程序获取必要的值并将其设置为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
}

答案 1 :(得分:1)

您可以像这样修改Form2的构造函数

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
    }
}

当你创建表单时,你会传递这样的项目

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