0

I'm using an SqlDataReader to read to a collection of custom type , but all I'm getting is the final row of the DataTable repeated, rather than a full table of information. Help would be gratefully received.

using (connection)
        {

            using (SqlCommand command = new SqlCommand(query, connection))
            {
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        lineData.Column1 = reader.GetValue(0).ToString();
                        lineData.Column2 = reader.GetValue(1).ToString();
                        lineData.Column3 = reader.GetValue(2).ToString();
                        lineData.Column4 = reader.GetValue(3).ToString();
                        lineData.Column5 = reader.GetValue(4).ToString();
                        lineData.Column6 = reader.GetValue(5).ToString();
                        lineData.Column7 = reader.GetValue(6).ToString();
                        lineData.Column8 = reader.GetValue(7).ToString();
                        columnData.Add(lineData);
                    }
                }
            }
        }

 foreach (var item in columnData)
        {
            Label.Text += item.Column1.ToString() + item.Column2.ToString() + item.Column3.ToString() + item.Column7.ToString();
        }
1
  • the code seems to be fine... can you upload your results(such as screen shots). and where did you declare columnData and why outside the loops? Commented Mar 20, 2017 at 0:54

2 Answers 2

1

lineData should be declared within while loop. If it was declared before the code you uploaded, then you're referencing the same instance for every data row. Try change code to following;

while (reader.Read())
                {
                    lineData = new LineData();//like that
Sign up to request clarification or add additional context in comments.

1 Comment

Knew it was something dumb. Thanks!
0

lineData must be declared during the cycle at that time. If it is declared before the code you uploaded, you to the same instance for each row of data. Try to change the code on the following;

Comments

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.