将 ASP.NET 按钮添加到 CodeBehind 中的 List

本文关键字:List 中的 CodeBehind ASP NET 按钮 添加 | 更新日期: 2023-09-27 18:32:01

我有 2 个asp:button称为 ShowSubmit 。它们在.designer.cs中声明为:

protected global::System.Web.UI.WebControls.Button Show;
protected global::System.Web.UI.WebControls.Button Submit;

我想将它们添加到List<Button>

List<Button> buttons = new List<Button> {Show,Submit};

它不让我这样做。 2 个错误表明

字段初始值设定项 不能引用非静态字段、方法或属性。

非静态对象是ShowSubmit。所以我认为我没有将它们添加到初始值设定项的列表中。

List<Button> buttons = new List<Button> ();
buttons.Add(Show);

但是VS告诉我buttonsShow是字段,但我像类型一样使用它们。谁能告诉我正确的方法?


更改按钮名称后的类:

public partial class _Default : Page
    {
        List<Button> buttons = new List<Button> ();
        buttons.Add(btnShow);
// some click events below
}

解决方案:解决方案是:初始化列表或将元素添加到列表中 Page_Load

public partial class _Default : Page
    {
        private List<Button> tableButtons;
        protected void Page_Load(object sender, EventArgs e)
        {
         tableButtons= new List<Button>();
         tableButtons.Add(btnSubmit);
            tableButtons.Add(btnShow);
        }
}

将 ASP.NET 按钮添加到 CodeBehind 中的 List<T>

如果按钮在同一窗体上,您可以执行以下操作

List<Button> buttons = this.Controls.OfType<Button>().ToList();

或您的原始代码

List<Button> buttons = new List<Button>
{
    Show, Submit
}; 

看起来你的代码可以工作,但是我想解释一下为什么,以便将来可以帮助你。

收到这些错误的原因是,您尝试将代码放在 _Default 的类定义中。 在类定义中,您可以定义字段、属性、方法和其他一些不值得讨论的内容,但重要的是您不能在定义中放置任何任意代码。

您需要将代码放在类的方法中,以便它正确编译和运行。 但是,由于您在 Web 窗体中执行此操作,因此还需要通过将代码放置在 ASP.NET 生命周期事件之一(如 Page_Load)中或放置在其中一个生命周期事件调用的方法中来调用代码。

希望这有帮助。 干杯。