c# - 从 ASP.net webform 中的 c# 类调用方法

标签 c# asp.net

我正在关注 youtube 教程,以便将我的 sql 数据库中的图像显示到 GridView 中,并且我几乎是一步一步地遵循编码。但是,在创建 Web 表单并从我刚刚创建的公共(public)类调用 a 方法到 Web 表单的 page_load 方法时,我似乎遇到了问题。不知道怎么回事

这是我的类(class)的样子:

public class Employee
{
    public int EmployeeID { get; set; }
    public String Name { get; set; }
    public String Gender { get; set; }
    public String Photo { get; set; }
}

public class EmployeeDataAccessLayer
{

    public  static List<Employee> GetAllEmployees()
    {
        List<Employee> listEmployees = new List<Employee>();

        string CS = ConfigurationManager.ConnectionStrings["DBSC"].ConnectionString;
        using(SqlConnection con = new SqlConnection(CS))
        {
            SqlCommand cmd = new SqlCommand("Select * from Employee", con);
            con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();

            while(rdr.Read())
            {
                Employee employee = new Employee();
                employee.EmployeeID = Convert.ToInt32(rdr["EmployeeID"]);
                employee.Name = rdr["Name"].toString();
                employee.Gender = rdr["Gender"].toString();
                employee.Photo = rdr["PhotoPath"].toString();

                listEmployees.Add(employee);
            }
        }
        return listEmployees;
    }
}

在网络表单的代码页中,这就是我想要做的:

protected void page_Load(object sender, EventArgs e)
{
   EmployeeDataAccessLayer.GetAllEmployees();
}

但是我在“EmployeeDataAccessLayer.GetAllEmployee();”中遇到错误那表示上下文中不存在后面的行

提前致谢!

最佳答案

您必须将代码文件放在 app_code 文件夹中,以便页面可以直接访问它。此外,您还必须将构建操作从 Content

更改为 Complile

右键单击app_code中的代码文件,从上下文菜单中选择属性,然后更改Build Action。

enter image description here

关于c# - 从 ASP.net webform 中的 c# 类调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23823563/

相关文章:

c# - 如何区分 Null 或 Empty ?根据什么标准处理 Null 和 Empty?

C# : Looping forever foreach CheckedListBox item

c# - (web.config|app.config) 中的配置设置与静态类对象

c# - 简单的聊天应用信号器

c# - unity texture2d EncodeToJPG 透明黑色

c# - 如何根据条件将 VIew 模型的属性绑定(bind)到 DataTrigger Setter?

c# - 全局捕获按键,但无论焦点如何,仅抑制当前应用程序和子窗​​口

c# - 访问 ASP.NET 表中的控件

c# - 为什么验证后为 false HttpContext.Current.Request.IsAuthenticated

asp.net - 如何从自托管 nancy 更改为 iis 下