Reputation: 169
List<T> returnList = new List<T>();
conn.Open();
SqlCommand sCmd = new SqlCommand(query, conn);
SqlDataReader dataReader = sCmd.ExecuteReader();
T t = new T();
PropertyInfo[] p = o.GetType().GetProperties();
while(dataReader.Read())
{
for (int i = 0; i < p.Length; i++)
{
Console.WriteLine(p[i].GetValue(t)+" "+p[i].PropertyType+"
"+dataReader[i].GetType());
p[i].SetValue(dataReader[i], t);
}
returnList.Add(t);
}
return returnList;
I want to set the value of specific property at run time from sqldatareader object. But i am getting an exception of target type mismatch even though both references are of the same type
Upvotes: 1
Views: 568
Reputation: 4796
You have two problems here. The main one is that you make a wrong call to SetValue()
.
From MSDN:
public void SetValue(object obj, object value)
So actually you are calling the method with the wrong placed arguments. Do this and it should be fine:
p[i].SetValue(t, dataReader[i]);
The second problem that you will encounter is that at the end your list will contain only the same object, because you create a new object only once (T t = new T();
. To solve it, you must place this line inside your while
loop.
Also, use using for cleaner code and because you should dispose your command at the end... And close your connection.
All in all, this is the final code:
List<T> returnList = new List<T>();
conn.Open();
using (SqlCommand sCmd = new SqlCommand(query, conn))
{
SqlDataReader dataReader = sCmd.ExecuteReader();
PropertyInfo[] p = o.GetType().GetProperties();
while(dataReader.Read())
{
T t = new T();
for (int i = 0; i < p.Length; i++)
{
Console.WriteLine(p[i].GetValue(t)+" "+p[i].PropertyType+" "+dataReader[i].GetType());
p[i].SetValue(t, dataReader[i]);
}
returnList.Add(t);
}
}
conn.Close();
return returnList;
Upvotes: 1