如何从另一个表单填充用户控件内的列表视图

时间:2017-06-16 10:45:58

标签: c# winforms

我在用户控件中有一个List视图,该用户控件放在MDI表单中,现在我需要做的是我必须根据MDI菜单点击填充列表视图。我尝试了下面的方法,但它没有工作,方法被触发但列表视图没有得到更新。这是我的示例代码 用户控制

public ucQuickLaunch()
    {
        InitializeComponent();
        ListFill("Loaded..");
    }
    public void ListFill(string Message)
    {
        try
        {
            ListViewItem myitem = new ListViewItem();
            myitem.Text = DateTime.Now.ToLongTimeString().ToString();
            myitem.SubItems.Add(Message);
            ListViewStatus.Items.Add(myitem);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

MDI菜单点击

    public  ucQuickLaunch objQuickLaunch=new ucQuickLaunch();
    private void newToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FrmGeneral frm = new FrmGeneral();
        FrmGeneral open = Application.OpenForms["FrmGeneral"] as FrmGeneral;
        if (open == null)
        {
            frm.MdiParent = this;
            frm.Show();
            objQuickLaunch.ListFill("General button clicked");
        }
        else
        {
            open.Activate();
            if (open.WindowState == FormWindowState.Minimized)
            {
                open.WindowState = FormWindowState.Normal;
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

我假设您已将自定义控件(ucQuickLaunch)放置在表单(FrmGeneral)上。如果是这样,您需要添加将该控件填充到表单的方法:

    public partial class FrmGeneral : Form
    {
        public FrmGeneral()
        {
            InitializeComponent();
        }

        public void ListFill(string value)
        {
            objQuickLaunch.ListFill(value);
        }
    }

和你的菜单:

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmGeneral open = Application.OpenForms["FrmGeneral"] as FrmGeneral;
            if (open == null)
            {
                FrmGeneral frm = new FrmGeneral();
                frm.MdiParent = this;
                frm.ListFill("General button clicked");
                frm.Show();
            }
            else
            {
                open.Activate();
                if (open.WindowState == FormWindowState.Minimized)
                {
                    open.WindowState = FormWindowState.Normal;
                }
            }
        }