tags:

views:

18

answers:

3

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();
}  
A: 

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.

Oded
You beat me to it...
ck
+2  A: 

Use a generic List instead, it has several advantages:

List<String> selectAnswer = new List<String>(); 
while (rdr.Read())
{
    selectAnswer.Add(rdr[0].ToString());
}  
Tim Schmelter
A: 

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();
Pedro