我在Form1中有一个listView1,在Form2中有一个向Form1的listView1添加元素的方法。 我收到listView1不存在的错误。如何删除此错误。 我的代码是
窗体2:
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();
}
答案 0 :(得分:1)
请使用此示例代码使用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)
{
}
}
}