I am trying to set the value of a class variable based on a string. I am querying a database for my data which returns a FieldName which should map the name of a variable for my class.
I have been able to get a list of the variables for the class and check if that class variable is equal to the FieldName returned.
However I am unable to set the value for this instance of my class.
Appointment Class:
public class Appointment
{
public int Id { get; set; }
public int EmployeeId { get; set; }
public string EmployeeFullName { get; set; }
public int SupervisorId { get; set; }
public string SupervisorFullName { get; set; }
public string Department { get; set; }
public int AppointmentType { get; set; }
public int EmploymentType { get; set; }
}
I initialise an instance of the Appointment Class earlier in this function, however here is the code where I try to assign the value depending on the FieldName.
appointment = new Appointment{//Assigned other values based on other query}
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
SqlCommand command = new SqlCommand(querySelectFields, connection);
connection.Open();
BindingFlags bindingFlags = BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.Static;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
foreach(FieldInfo field in typeof(Appointment).GetFields(bindingFlags))
{
// Extracts the field name from original format of "<fieldName>k__BackingField"
string tempFieldName = field.Name.Substring(1);
string fieldName = tempFieldName.Substring(0, tempFieldName.Length- 16);
if ((String)reader["FieldName"] == fieldName)
{
//This is where it errors
field.SetValue(null, int.Parse(reader["SelectValueID"].ToString()));
}
}
}
}
The error that I am gettings is:
Exception Details: System.Reflection.TargetException: Non-static field requires a target.
I understand that this is caused by putting null as the first parameter in that call, however I cannot seem to find the correct way to do this.
Ideally I would be able to do something like this:
if((String)reader["FieldName"] == fieldName)
{
appointment.field = int.Parse(reader["Value"].ToString());
}
And that would be the same as:
if((String)reader["FieldName"] == "AppointmentType")
{
appointment.AppointmentType = int.Parse(reader["Value"].ToString());
}