我正在使用 C# 动态创建一个表格,并向每个单元格添加按钮。我需要为每个按钮分配 ID,以便稍后识别它们。我为此使用了以下代码。
bt.ID = rowIndex + c.ToString(); //bt.ID = "newID";
但是当我稍后尝试访问此按钮时,它给了我一个错误。
Button seatButton = (Button)this.FindControl("a1");
seatButton.BackColor = Color.Red; //Gives an error here
seatButton.Enabled = false; //Gives an error here
我认为问题出在更改按钮 ID 上。我需要知道这个错误的原因和解决方法..
最佳答案
此处,语句中的 seatButton
必须为 null:
Button seatButton = (Button)this.FindControl("a1");
您可以先查找控件的占位符,然后获取按钮控件,或者在所有页面控件中递归搜索,而不是仅仅执行 this.FindControl
。
方法一:使用ContentPlaceHolder方式。
ContentPlaceHolder contentPH = (ContentPlaceHolder)this.Master.FindControl("MyContentPlaceHolder");
Button seatButton = (Button)contentPH.FindControl("a1");
方法二::通过页面控件递归搜索。
从代码的适当部分调用一次 getControl 方法
GetControl(Page.Controls);
//方法如下:
private void GetControl( ControlCollection controls )
{
foreach (Control ctrl in controls)
{
if(ctrl.ID == "a1")
{
seatButton = (Button)ctrl;
}
if( ctrl.Controls != null)
// call recursively this method to search nested control for the button
GetControl(ctrl.Controls);
}
}
关于c# - 如何使用C#代码更改asp按钮ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18681283/