Question

I'm trying to read out data from a set query row by row and put each record in an object in a list of objects, but I don't know what the datatype is for a single record in SqlDataReader.

List<Response> responseList = new List<Response>();
for (int i = 0; reader.Read(); i++) //reader is the SqlDataReader
    responseList.Add(new Response(reader[i]));

What datatype do I set the Response constructor's parameter as?

public Response(IDataRecord r) //what's the data type suppose to be?
{

}
Was it helpful?

Solution

reader[i] is an index to the i-th field of the current record. For example, if your query is

SELECT ID, FNAME, LNAME, ADDRESS FROM CUSTOMERS

then your loop tries to pass to your function the field ID (i=0) of the first record at the first loop, the field FNAME (i=1) of the second record in the second loop, the field LNAME (i=2) of the third record in the third loop and then the field ADDRESS (i=3) of the fourth record, finally (if you have more than four records retrieved) the code crashes with an out of range exception (i=4 but the columns are just 4)

You need to build an object Response and then fill its properties before adding it to the list.
So, still supposing that your object Response has four properties named ID, FirstName, LastName, Address then you write

List<Response> responseList = new List<Response>();
while(reader.Read()) 
{
      responseList.Add(new Response()
      {
           ID = reader[0].ToString(), 
           FirstName = reader[1].ToString(), 
           LastName = reader[2].ToString(),
           Address = reader[3].ToString()
      };
}

OTHER TIPS

At first change your reading condition, secondly you can create a List <string> for saving your data.

List<string> responseList = new List<string>();

While (reader.Read())
{
  responseList.Add(reader[i]).ToString());
}

take in account that now, all fields are saved in the same List (response List), if you wish to save each field separately: (assuming you selecting 3 fields in your sql query)

List<string> List1 = new List<string>();
List<string> List2 = new List<string>();
List<string> List3 = new List<string>();
 While (reader.Read())
    {
      List1.Add(reader[0]).ToString());///1st field of select
      List2.Add(reader[1]).ToString());///2nd field of select
      List3.Add(reader[2]).ToString());///3rd field of select

    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top