简体   繁体   中英

Access a ListView located in a UserControl from the MainForm in Winforms

I have an app that uses a side menu, and for each button (there are 3) on the left side menu, it changes the pages shown.

I tried doing it with multiple panels, but it's a nightmare to maintain in designer, and it's probably not a very good programming habit, I expect.

So I search and found what seemed to be a great idea: UserControl . But as usual, it's not that simple (for a badly self-taught guy like me)

The general flow of the program is as follows:

  • a Btn_uc1_Check button that gathers informations and displays them in a uc1_ListView,
  • a Btn_uc2_Seek button that gathers informations on the net based on the uc1_ListView , and displays them on uc2_ListView,
  • a Btn_uc3_compile that compiles the info from uc2_ListView into a file,
  • a Clear button that clears the ListView depending on the UserControl on screen.

Now to the problem:

  • How on earth do I gain access to a ListView located in a UserControl to be able to read, clear, and add items from the MainFrom or from another UserControl?

I searched and honestly found nothing corresponding to what I needed?

Quite many questions.

  1. You can gain access to any controls in UC. Just change the property "Modifiers" of the ListView in your UC to "Public".

例1

  1. Set that method to public. Do not use keyword "static". Each control in your form is an instance of a class, not a static class actually. In the main form, create a button and double click on it in VS designer. A method will automatically generated, something like private void button1_Click . When the button is clicked, all of the code lines in button1_Click will run.

  2. Create a public event handler of your user control, then pass the method in main to the handler.

So the UC class will be similar to this:

public event EventHandler button_UC_Click_handler;

    public UserControl1()
    {
        InitializeComponent();
    }

    private void button_UC_Click(object sender, EventArgs e)
    {
        button_UC_Click_handler.Invoke(sender, e);
    }

In main form:

public MainForm()
    {
        InitializeComponent();
        userControl11.button_UC_Click_handler += UserControl11_button_UC_Click_handler;
    }

    private void UserControl11_button_UC_Click_handler(object sender, EventArgs e)
    {
        MessageBox.Show("You have clicked it!");
    }

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM