问题
I have 2 forms: a main form and a second form with only a listview in which users can make a selection. Once the listview item is activated with a double click, I want a label on the main form to display the text of the item that was activated. Here is my code (not working); why is this wrong? Thanks
Main Form:
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
/* for populating the process list when the user clicks display process button */
private void DisplayProcessButton_Click(object sender, EventArgs e)
{
Process_List plopen = new Process_List();
plopen.Show();
Process[] process = Process.GetProcesses();
foreach (Process prs in process)
{
plopen.listView1.Items.Add(prs.ProcessName);
}
}
Second Form:
private void listView1_ItemActivate(object sender, EventArgs e)
{
MainForm mf = new MainForm();
mf.label1.Text = e.ToString();
Close();
}
回答1:
Here's what you should do! On your second form, do this
public MainForm parentForm;
public void SecondForm(MainForm form)
{
InitializeComponent();
parentForm = form;
}
And...
private void listView1_ItemActivate(object sender, EventArgs e)
{
parentForm.label1.Text = e.ToString();
}
Then in your main form...
public SecondForm secondform;
public void MainForm()
{
InitializeComponent();
secondform = new SecondForm(this);
}
And when you open your SecondForm use this wherever you want!
secondform.Show();
By doing this, you can transfer information form form to form back and forth. I use this all the time with every one of my forms. It's very very useful! If you have any questions please let me know!
来源:https://stackoverflow.com/questions/41007088/change-label-text-via-listview-itemactivate