Change Label Text via ListView ItemActivate [duplicate]

筅森魡賤 提交于 2019-12-24 09:03:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!