0

I am selecting data from database and in while loop, i want it store all data in one variable. How to do that? The variable selectAnswer is string array type .

I used this code but this give error. Modify this code.

string selectAnswer[] = new string[];
while (rdr.Read())
{
    selectAnswer[] = rdr[0].ToString();
}  

3 Answers 3

2

Use a generic List instead, it has several advantages:

List<String> selectAnswer = new List<String>(); 
while (rdr.Read())
{
    selectAnswer.Add(rdr[0].ToString());
}  
Sign up to request clarification or add additional context in comments.

Comments

0

Your question is quite confusing. You want to store the data into a single variable or into a single string? If that's the case why not use a StringBuilder instead.

StringBuilder answer = new StringBuilder();
while (rdr.Read())
{
    answer.AppendLine(rdr[0].ToString());
}

But I'm still not sure if I undestood correctly.

Other option is using a list:

IList<string> answer = new List<string>();
while (rdr.Read())
{
    answer.Add(rdr[0].ToString());
}
answer.ToArray();

Comments

0

You are trying to assign a single string to the whole array instead of a single string per array item.

You can use a List<string> instead of an array of strings and simply add items to it:

IList<string> selectAnswer = new List<string>();
while (rdr.Read())
{
    selectAnswer.Add(rdr[0].ToString());
}

For this to work with an array, you will first need to declare the array variable with the number of items in the data reader and have a counter for which index you are inserting on.

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.