c# - 如何使用C#代码更改asp按钮ID

标签 c# asp.net

我正在使用 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/

相关文章:

c# - 附加属性的 XML 文档注释放在哪里?

c# - 在 WPF 中将参数传递给 StartupUri

c# - 如何调试崩溃的转储文件?

asp.net - 如何排除XML中的根节点来显示菜单?

asp.net - 我可以获得更高质量的图表吗?

c# - 在 C# 中使用/或\\for 文件夹路径

c# - Xamarin.Android pdf 生成器

c# - 扩展方法找不到类型的定义

c# - 是否可以将背景位置添加到 img/asp :image tag

jquery - 使用asp.net更改jquery ajax中的css