【问题标题】:Create class Employee and Get all employees to a GridView using SELECT创建类 Employee 并使用 SELECT 将所有员工获取到 GridView
【发布时间】:2017-04-25 07:05:05
【问题描述】:

如下所示,我有员工类和员工列表,但我得到空白的 ASP.NET 页面。没有显示 GridView,我也没有收到任何错误消息。 我在做什么错了?

public class Employee
{
    public int EmployeeId { set; get; }
    public string FirstName { set; get; }
    public string LastName { set; get; }
}

还有员工列表

public List<Employee> GetEmployeeList()
{
    try
    {
        string CS = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
        {
            empList = new List<Employee>();

            string sqlSelectString = "SELECT * FROM Employee";
            command = new SqlCommand(sqlSelectString, conn);
            command.Connection.Open();

            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                Employee emp = new Employee();
                emp.EmployeeId = reader.GetInt32(reader.GetOrdinal("ID"));
                emp.FirstName = reader.GetString(reader.GetOrdinal("FirstName"));
                emp.LastName = reader.GetString(reader.GetOrdinal("LastName"));

                empList.Add(emp);
            }
            command.Connection.Close();
            return empList;
        }

    }
    catch (Exception ex)
    {
        ErrorMessage = ex.Message;
    }
    return null;

}

然后在pageLoading中

protected void Page_Load(object sender, EventArgs e)
{
    Employee employee = new Employee();
    List<Employee> employeeList;

    employeeList = employee.GetEmployeeList();
    GridView1.DataSource = employeeList;
    GridView1.DataBind();

}


最后我的 Gridview:

<form id="form1" runat="server">
    <div>

        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>

    </div>
</form>


提前谢谢你!

【问题讨论】:

  • 显然出了点问题。在每次读取记录后放置一个Debug.Print,并查看在调试会话期间输出中是否出现任何内容
  • @fnostro ,谢谢 Fnostro ......我发现了自己的错误...... ;) 我让你在每个喜欢后使用 tostring() emp.FirstName = reader["FirstName"].ToString() ;
  • 不客气。

标签: c# asp.net gridview data-access-layer


【解决方案1】:

解决方案是:

emp.EmployeeId = Convert.ToInt32(reader["EmployeeId"].ToString());
emp.FirstName = reader["FirstName"].ToString();
emp.LastName = reader["LastName"].ToString();

【讨论】:

    猜你喜欢
    • 2021-03-01
    • 2020-04-07
    • 1970-01-01
    • 2022-01-18
    • 2022-01-20
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多