【问题标题】:Populating data in dropdown menu在下拉菜单中填充数据
【发布时间】:2012-10-06 22:19:17
【问题描述】:

我是 c# 的新手,所以有点卡在我认为是一个非常简单的模块上。我只需要在下拉菜单中显示数据,但在绑定时出现一些错误......或者我什至会在绑定之前说。这就是我想要做的事情。如果我犯了一个非常简单的错误,我真的很抱歉,但我已经尽力了,现在我想我需要一些指导。

CustomService.cs

public partial class CustomService
{
public List<Code> GetDepartment(bool activeOnly)
    {
        List<Code> retVal = new List<Code>();
        ---some code----
        return retVal;
    }
     }

ProgramList.ascx.cs

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            List<Code> dept = new List<Code>CustomService.GetDepartment(true);
            ddlDepartment.DataSource = dept;
            ddlDepartment.DataBind();
         }
    } 
   //error an object reference is required for an nonstatic field, method or Property CustomService.GetDepartment(true);

【问题讨论】:

    标签: c# asp.net data-binding drop-down-menu


    【解决方案1】:

    我认为这会有所帮助。

     CustomService custS = new CustomService();
        ddlDepartment.DataSource = custS.GetDepartment(true);
        ddlDepartment.DataBind(); 
    

    【讨论】:

      【解决方案2】:

      为了能够调用 GetDepartment 方法,您需要创建一个新的 CustomService 实例:

      CustomService service = new CustomService();
      service.GetDepartment(true);
      

      或将方法设为静态:

      public static List<Code> GetDepartment(bool activeOnly) { }
      

      但是,如果将其设置为静态,则该方法使用的驻留在类中的每个变量也必须是静态的。

      【讨论】:

      • GetDepartment 不是静态方法
      • 啊!抱歉,没有注意到它在不同的班级。让我失望的是 Page_Load 周围缺少类定义
      【解决方案3】:

      你忘了先创建对象,然后你可以调用方法

      另一件事是你只需要像我在下面那样直接分配值,不需要创建任何新列表

      检查下面对你有用的代码

      CustomService custsrv = new CustomService();
      List<Code> dept = custsrv.GetDepartment(true);
      

      【讨论】:

      • CustomService 是不同项目中的一个单独的帮助类我已经使用 Prod.Integration.DataModel 为该项目添加了 dll;在页面顶部...
      • 我还需要为它创建一个实例吗??
      • 好的现在我没有错误..它编译得很好,但我没有得到下拉列表中的数据列表??对不起,还有一个问题
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 2014-01-04
      • 2017-08-02
      相关资源
      最近更新 更多