Search code examples
c#winformsflowlayoutpanel

How to handle click event of two FlowLayoutPanel with some dynamically created controls?


I have two FlowLayoutPanel controls on the same form with some controls on both of them. What O want is that if FlowLayoutPanel1 controls are clicked, I want to change label1.Text and if FlowLayoutPanel2 controls are clicked, I want to change label2.Text.

Here is my code to add controls in both FlowLayoutPanel.

public void Load_DFlavours(FlowLayoutPanel FLP)
{
    try
    {
        FLP.Controls.Clear();
        using (SQLiteConnection con = new SQLiteConnection(AppSettings.ConnectionString()))
        {
            con.Open();
            using (SQLiteDataAdapter sda = new SQLiteDataAdapter("Select distinct(Flavour_Name) From Flavours Where Category_Name = 'Flavours' Order By Flavour_Name", con))
            {
                DataTable dt = new DataTable();
                sda.Fill(dt);
                foreach (DataRow dr in dt.Rows)
                {
                    RadioButton rb2 = new RadioButton();
                    rb2.AutoSize = true;
                    rb2.Font = new Font("Segoe UI Semilight", 10F);
                    rb2.Margin = new Padding(2);
                    rb2.Text = dr["Flavour_Name"].ToString();
                    rb2.UseVisualStyleBackColor = true;
                    rb2.Tag = dr["Flavour_Name"].ToString();

                    FLP.Controls.Add(rb2);

                    rb2.CheckedChanged += Rb2_CheckedChanged;
                }
            }
            con.Close();
        }
    }
    catch (SQLiteException se)
    {
        MessageBox.Show(se.Message);
    }
}

Clickevent Code:

private void Rb2_CheckedChanged(object sender, EventArgs e)
{
    RadioButton rb2 = (RadioButton)sender;
    string flavour = rb2.Tag.ToString();

    //I want to do something here if flowlayoutPanel 1 control is 
    clicked change the label1.Text and if flowlayoutPanel 2 control is 
    clicked change the label2.text

    //I have tried this
    if(rb2.Checked)
    {
        label1.text = flavour;
    }
}

How to know which FlowLayoutPanel Controls are clicked?

I can do this by creating multiple methods but I want to do this work on the same method.

For more clarification, see this image:

See the image


Solution

  • Don't have a computer to check right now, but I assume this should work

    if (rb2.Checked)    
    {
        if (rb2.Parent.Name == "flowlayoutPanel1")
        {
            label1.Text = flavour;
        }
        else if (rb2.Parent.Name == "flowlayoutPanel2")
        {
            label2.Text= flavour;
        }
    }