c# listView上的两个窗口

本文关键字:两个 窗口 listView | 更新日期: 2023-09-27 18:12:05

我在Form1和Form2中有一个listView1的方法,它将元素添加到Form1的listView1。我得到一个错误,listView1不存在。我怎样才能消除这个错误?我的代码是

Form2:

    public static string s;
    public void button1_Click(object sender, EventArgs e)
    {
        s = textBox1.Text;
        ListViewItem lvi = new ListViewItem(DodajWindow.s);
        listView1.Items.Add(lvi);
        this.Close();
    }

c# listView上的两个窗口

请使用这个示例代码使用2个表单,

Form1代码

public delegate void ListViewAddDelegate(string text);
namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public void AddItem(string item)
        {
            listView1.Items.Add(item);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            ListViewAddDelegate Del = new ListViewAddDelegate(AddItem);
            Form2 ob = new Form2(Del);
            ob.Show();
        }
    }

}

Form2代码

namespace WindowsFormsApplication2
{
    public partial class Form2 : Form
    {
        public ListViewAddDelegate deleg;
        public Form2()
        {
            InitializeComponent();
        }
        public Form2(ListViewAddDelegate delegObj)
        {
            this.deleg = delegObj;
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (!textBox1.Text.Equals(""))
            {
                deleg(textBox1.Text);
            }
            else
            {
                MessageBox.Show("Text can not be emopty");
            }
        }
        private void Form2_Load(object sender, EventArgs e)
        {
        }
    }
}