Search code examples
c#winformsuser-controls

C# UserControl - Get property value each control inside UserControl on Click event


I have a custom UserControl like this (Its name is TP1CustomListView):

Picture for my UserControl

I used a TableLayoutPanel with 2 columns to hold a picture (on the first column) and another TableLayoutPanel (on the second column). The TableLayoutPanel in the second column has 3 rows to hold 3 TextBox.

I wrote a Click event for the PictureBox in UserControl like this:

 //events
        public new event EventHandler Click
        {
            add { picbox.Click += value; }
            remove { picbox.Click -= value; }
        }

In Form1 I have 10 UserControls like the picture I attached to the top of the topic. I have written a Click event for all UserControl in my Form1. I tried to cast the sender of each UserControl on Click to get 3 value of 3 TextBox inside that UserControl. But the result I got is "NULL".

This is my code for Click event:

  public Form1()
        {
            InitializeComponent();
            foreach (Control c in this.Controls)
            {               
                TP1CustomListView ctLV = c as TP1CustomListView;
                if (ctLV != null)
                {
                    ctLV.Click += ctLV_Click;

                }
            }
        } 

  void ctLV_Click(object sender, EventArgs e)
        {

            TP1CustomListView customView = sender as TP1CustomListView;

              if(customView!=null)
              {
                  MessageBox.Show(customView.subtbTitle.Text + customView.subtbContent.Text + customView.subtbFooter.Text);
              }
        }

This is constructor and sub-controls in my TP1CustomListView (UserControl):

 //sub controls
        public PictureBox subPicbox;
        public TextBox subtbTitle;
        public TextBox subtbContent;
        public TextBox subtbFooter;
        public TP1CustomListView()
        {
            InitializeComponent();
            subtbTitle = txtTitle;
            subtbContent = txtContent;
            subtbFooter = txtFooter;
            subPicbox = picbox;
            tableLayoutPanel1.Dock = DockStyle.Fill;
        }

Hope everyone can give me some advice or any solution to my issue. Thank you!


Solution

  • You should handle the PictureBox's click event inside the user control, and raise a click event from the UserControl when that happens.

    Inside your user control you should have something like this:

    picturebox.Click += picturebox_click;
    
    
    private void picturebox_click(object sender, EventArgs e)
    {
        var handler = this.Click;
        if(handler != null)
        {
            handler(this, e);
        }
    }
    

    That way, your click on the picturebox triggers a click on the user control, and that click is what you actually listen for in your form.