gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:14:03 25 4
gpt4 key购买 nike

我正在使用 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 必须是空的声明:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com