while (reader.Read())
{
newEmp.eid = (int)reader("EID");
newEmp.firstname = (string)reader("FirstName");
....
}
SqlDataReader to populate struct
-
17-06-2023 - |
Pregunta
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.
Solución
Otros consejos
load up the struct like this perhaps
while (reader.Read()) {
newEmp.lastname = reader.GetString(1);
newEmp.firstname = reader.GetString(2);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow