[英]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.我有一个 WebForm,它的控件是动态创建的,因为它们的数量可能会有所不同。 Each element is a Panel containing a TextBox, a DropDownList and a Button.
每个元素都是一个 Panel,其中包含一个 TextBox、一个 DropDownList 和一个 Button。
Each control is given a unique ID and all the buttons have the same clickEvent.每个控件都有一个唯一的 ID,并且所有按钮都具有相同的 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.
在 clickEvent 的代码中,我想获取 presedButton 所属的面板的 ID,以便我可以从该面板的 DropDownList 和 TextBox 中访问所选值。
How can I do the above?我该怎么做以上?
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:或通过控制 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.