How to find container of dynamically created button ASP.net

I have a WebForm whose controls are created dynamically as they can vary in number. Each element is a Panel containing a TextBox, a DropDownList and a Button.
Each control is given a unique ID and all the buttons have the same clickEvent. Inside the code of the clickEvent, I want to obtain the ID of the panel in which the presedButton belongs so I can access the chosen value from that Panel’s DropDownList and the text from the TextBox.
How can I do the above?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

private void button1_Click(object sender, EventArgs e)
    {
        var panelId = ((Button)sender).Parent.ID;

    }

Or you could get the controls directly

private void button1_Click(object sender, EventArgs e)
    {

        var myTextbox = ((Button)sender).Parent.Controls.OfType<TextBox>().FirstOrDefault();
        var myDropDownlist = ((Button)sender.Parent.Controls.OfType<DropDownList>().FirstOrDefault();

    }

or by control ID:

private void button1_Click(object sender, EventArgs e)
    {

        var myTextbox = ((Button)sender).Parent.Controls.OfType<TextBox>().Where(x => x.ID == "textboxID").SingleOrDefault();
        var myDropDownlist = ((Button)sender).Parent.Controls.OfType<DropDownList>().Where(x => x.ID == "dropdownlistID").SingleOrDefault();

    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x