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

标签 c# asp.net

我有 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个错误说明

a field initializer cannot reference the non-static field, method, or property.

非静态对象是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中初始化List或向List中添加元素:

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);
        }
}

最佳答案

如果按钮在同一个表单上,你可以执行以下操作

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

或您的原始代码

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

关于c# - 将 ASP.NET 按钮添加到 CodeBehind 中的 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35002867/

相关文章:

asp.net - 内容处置 :What are the differences between "inline" and "attachment"?

c# - 在弹出框中输入文本

c# - 我是否需要处理来自 Request.CreateResponse() 的 HttpResponseException?

css - 使用 css 旋转 GridView 标题

asp.net - 如何在 ASP.NET MVC 模型中保存选定的 DropDownList 值以进行 POST?

asp.net:部分类和继承

c# - 我可以在 C# 中同时创建 2 个子目录吗?

c# - ForEach 与 EditorFor

c# - 如何防止我的机器人回复 Slack 中的每条消息?

c# - Unity Hololens 崩溃