如何在静态方法中访问下拉列表



我在home.aspx中做了一个DropDownListhome.aspx.cs页面中我想在静态方法中访问它。怎么可能?我无法以静态方法访问它。请帮助我..

不,这是不可能的。

这是许多语言的基本规则。静态方法无法访问特定于实例的任何内容。ASP.NET 上的DropDownList实例就是这样。一个实例变量。静态方法适用于所有实例。

要得到你想要的东西......你需要将一个实例传递到其中。像这样:

public class ObjectA {
    public string Name { get; set; }
    public static string GetName(ObjectA instance) {
        return instance.Name;
    }
}

(是的,这是一个可怕的例子。

因此,对于 ASP.NET 页面,您可以执行以下操作:

public void Page_Load(object sender, EventArgs e) {
    doSomethingWith(dropDownList1);
}
public static void doSomethingWith(DropDownList dropDown) {
    // use the dropdown variable here
}

DropDownList作为静态方法的参数传递,然后您可以从静态方法调用此实例的方法。

最新更新