I using delegate to pass data between 2 form MainForm;
publ开发者_如何学Cic delegate void PassData(ListViewItem itemss);
public PassData passdata;
private void ViewList_SelectedIndexChanged(object sender, EventArgs e)
{
passdata(ViewList.FocusedItem);
}
call PropertiesForm
Properties1 pro = new Properties1();
pro.Show();
In form2
public void f_pass(ListViewItem item)
{
this.item = item;
}
private void Properties1_Load(object sender, EventArgs e)
{
Main main = new Main();
main.passdata += new Main.PassData(f_pass);
}
When I run it have a error is null object at passdata(ViewList.FocusedItem);
You can create another constructor for the form that you want to pass data to. The constructor will take arguments of the type of data you want, but be sure that you call the default constructor by using the
: base()
It seems that you are call delegate befor it was created. As I understand correct You are intend to pass data from MainForm
to PropertiesForm
but initialization happens only during PropertiesForm
loading. Its very likely that you have architectural issue but for now just try to change your ViewList_SelectedIndexChanged
method as below:
public PassData passdata = null;
private void ViewList_SelectedIndexChanged(object sender, EventArgs e)
{
if(passdata != null)
{
passdata(ViewList.FocusedItem);
}
}
I think pass data between forms is not a good idea. Try use some middleman to contains data.
Do it this way,
public partial class Main : Form
{
public delegate void PassData(ListViewItem itemss);
public static event PassData PassDataEvent;
private void ViewList_SelectedIndexChanged(object sender, EventArgs e)
{
if (PassDataEvent != null)
{
PassDataEvent(ViewList.FocusedItem);
}
}
}
public partial class Properties1 : Form
{
public Properties1()
{
InitializeComponent();
this.Load += new EventHandler(Main_Load);
}
void Properties1_Load(object sender, EventArgs e)
{
Main.PassDataEvent += new Main.PassData(Main_PassDataEvent);
}
void Main_PassDataEvent(ListViewItem itemss)
{
//do your logic.
}
}
精彩评论