1

我正在为我的 Gridview 使用 ObjectDataSource。我用来返回值的函数只是返回一个值,它是表中的最后一个值。我要进行哪些更改以返回所有值。

public class Employees
    {
        public int e_number;
        public string e_name;
        public string e_designation;
        private SqlConnection conn = null;
        private SqlCommand cmd = null;
        private string constring = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;


        public Employees()
        {
            conn = new SqlConnection(constring);
            cmd = new SqlCommand();
        }
        public int Employee
        {
            get
            {
                return e_number;
            }
            set
            {
                e_number = value;
            }
        }

        public  string Name
        {
            get
            {
                return e_name;
            }
            set
            {
                e_name = value;
            }
        }
        public string Designation
        {
            get
            {
                return e_designation;
            }
            set
            {
                e_designation = value;
            }
        }   


        public Employees GetEmployee()
        {
            string strquery = "select [Number],[Name],[Designation] from [Users]";
            conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = strquery;
             SqlDataReader objSqlDataReader = cmd.ExecuteReader();
            int counter = 0;
           // ArrayList myObj = new ArrayList();
          //  Employees objEmployees = new Employees();
            Employees emp = null;

            //if (objSqlDataReader.Read())
            while(objSqlDataReader.Read())
            {
               emp = new Employees();
               // myObj[counter] = new Employees();
              //  Employees employee = new Employees();
                emp.Employee = (int)objSqlDataReader["Number"];
                emp.Name=(string)objSqlDataReader["Name"];
                emp.Designation = (string)objSqlDataReader["Designation"];



               // objEmployees.e_number = (int)objSqlDataReader["Number"];
               // objEmployees.e_name = (string)objSqlDataReader["Name"];
                //objEmployees.e_designation = (string)objSqlDataReader["Designation"];


            }

            conn.Close();
            return emp; 




            //return objEmployees;



        }
    }
}

我已经尝试了所有方法,例如制作对象数组,但我无法做到。请你告诉我要在我的代码中添加什么。

4

1 回答 1

1

您需要返回一份员工名单。您只返回一个,即退出循环后的最后一个实例:

public List<Employees> GetEmployees()
{
    ..
    List<Employees> emps = new List<Employees>();
    Employees emp = null;

    while (..)
    {
        emp = new Employees();
        ..
        emps.Add(emp);
    }

    return emps;
}
于 2012-04-20T14:07:35.360 回答