Question

There is a private "Employee" class object that mirrors the public struct "empStruct". I need to read in the rows values from the query using SQLReader to populate the struct and then set the object equal to the struct values. I think there is a simpler way but I am very new to this.

public struct empStruct
    {
        public int eid;
        public string lastname;
        public string firstname;
        public DateTime birthdate;
        public DateTime hiredate;
        public bool ishourly;
        public decimal payrate;
    }
        public static bool SelectEmployee(int eid)
    {
        empStruct SelectRecord = new empStruct();
        Employee newEmp = new Employee();
        string sqlText;

        sqlText = "SELECT EID,EID, LastName, FirstName, BirthDate, HireDate, IsHourly, PayRate ";
        sqlText += "FROM Employee ";
        sqlText += "WHERE EID = @EID ";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {

            SqlCommand command = new SqlCommand(sqlText, connection);
            command.CommandType = CommandType.Text;
            command.Parameters.AddWithValue("@EID", eid);
            connection.Open();

            SqlDataReader reader = command.ExecuteReader();

            //Call Read before accessing data.
            while (reader.Read())
            {
                ???
            }
            newEmp = SelectRecord;

        }

I understand that everything after "//Call Read..." is incomplete, I can't figure out exactly how this reader thing works.

Was it helpful?

Solution

while (reader.Read())
{
newEmp.eid = (int)reader("EID");
newEmp.firstname = (string)reader("FirstName");
....
}

OTHER TIPS

load up the struct like this perhaps

while (reader.Read())            {
   newEmp.lastname = reader.GetString(1);
   newEmp.firstname  = reader.GetString(2);


}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top