I'm getting an "An object reference is required for the non-static field, method, or property Skirmer_Final.Nyhed.FK_Nyhed_ID.get" error. And I can't figure out whats wrong.
My code
public class Nyhed
{
public int FK_Status_ID { get; set; }
public int FK_Nyhed_ID { get; set; }
public static List<Nyhed> GetByStatus(int ID, SqlConnection connection)
{
List<Nyhed> result = new List<Nyhed>();
using (var command = new SqlCommand("Select FK_Nyhed_ID from Status_Kan_Se_Nyhed where FK_Status_ID=@id"))
{
command.Connection = connection;
command.Parameters.AddWithValue("id", ID);
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Nyhed StatusKanSeNyhed = new Nyhed();
StatusKanSeNyhed.FK_Status_ID = ID;
StatusKanSeNyhed.FK_Nyhed_ID = reader.GetInt32(0);
result.Add(StatusKanSeNyhed);
}
}
finally
{
reader.Close();
}
foreach (Nyhed N in result)
{
N.status = Status.GetByID(FK_Status_ID, connection);
N.nyhed = Nyhed.GetByID(FK_Nyhed_ID, connection);
}
}
return result;
}
}
Can you see the error?
FK_Nyhed_ID
is a property. As such, you need to reference it through an object. I'm guessing the problem is here:
foreach (Nyhed N in result) {
N.status = Status.GetByID(FK_Status_ID, connection);
N.nyhed = Nyhed.GetByID(FK_Nyhed_ID, connection);
}
You previously referenced FK_Nyhed_ID
on the StatusKanSeNyhed
instance, so I'm guessing you'll want to reference N.FK_Nyhed_ID
below
foreach (Nyhed N in result) {
N.status = Status.GetByID(FK_Status_ID, connection);
N.nyhed = Nyhed.GetByID(N.FK_Nyhed_ID, connection); //<----- added object reference
}
I guess the you wanted to write
foreach (Nyhed N in result)
{
N.status = Status.GetByID(N.FK_Status_ID, connection);
N.nyhed = Nyhed.GetByID(N.FK_Nyhed_ID, connection);
}
and add the missing N.
FK_Status_ID
is an instance property so it cannot be accessed from a static method. You can either make it static or change your method to an instance method.
The problem is here:
foreach (Nyhed N in result)
{
N.status = Status.GetByID(FK_Status_ID, connection);
N.nyhed = Nyhed.GetByID(FK_Nyhed_ID, connection);
}
You are trying to read public member FK_Status_ID, whitch is accessible only though an instance of an object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.