1
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

3
  • At which line to you get this exception ? How do you know that your columns in your datareader are in the same order than your properties ? Commented Oct 12, 2017 at 5:53
  • 1
    the line in which i'm setting the value and I've written a class the order in which my columns are placed in the table Commented Oct 12, 2017 at 5:57
  • Could you add in your code the method signature ? (public/private List<T> myMethodName...) Commented Oct 12, 2017 at 6:05

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks that helped
@SohelAhmed If this answers your question, please mark it as the answer (the check mark next to the top of the answer). That way others will see that this question is answered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.