我有 2 asp:button
我们叫 Show
和 Submit
.它们在 .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.
非静态对象是Show
和 Submit
.所以我认为我没有将它们添加到初始化程序的列表中。
List<Button> buttons = new List<Button> ();
buttons.Add(Show);
但是 VS 告诉我 buttons
和 Show
是字段,但我像使用类型一样使用它们。谁能告诉我正确的做法?
更改按钮名称后的类:
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/