Click here to Skip to main content
16,018,802 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a Sql Database with many attributes. From there i want to take all the value of question attribute in an array named getQuestion Here Is my code
C#
vcon.Open();
  SqlCommand cmd = new SqlCommand("select question from examQuestion where tchId='123'", vcon);
  SqlDataReader dr = cmd.ExecuteReader();
  String[] getQuestion = { "" };
  int i = 0;

  while (dr.Read())
  {
      getQuestion[i] = dr.GetString(0);
      i++;
  }
  vcon.Close();

It is fine when database contain single value, But when database has more then one value it provide an Error "Index was outside the bounds of the array". What is the problem? Please Help me. I am very new at ASP.Net.
Posted
Comments
[no name] 20-Jul-13 11:27am    
Your getQuestion array only contains room for a single element because that is all you dimensioned it for. Use a List instead.

Try this way:
C#
vcon.Open();
SqlCommand cmd = new SqlCommand("select question from examQuestion where tchId='123'", vcon);
SqlDataReader dr = cmd.ExecuteReader();
ArrayList getQuestion = new ArrayList();
int i = 0;

while (dr.Read())
{ 
    getQuestion.Add((string)dr["question"]);//or getQuestion.Add((string)dr[0]);
}
vcon.Close();
 
Share this answer
 
Comments
sazzad37 20-Jul-13 11:44am    
ArrayList provides Reference Error.
sazzad37 20-Jul-13 11:47am    
getQuestion[0] is not allowed.
Kuthuparakkal 20-Jul-13 11:50am    
Post the full piece of code
use Generic List the Easy way
vcon.Open();
          SqlCommand cmd = new SqlCommand("select question from examQuestion where tchId='123'", vcon);
          SqlDataReader dr = cmd.ExecuteReader();
           System.Collections.Generic.List<string> LstQuestion = new System.Collections.Generic.List<string>();

          while (dr.Read())
          {
              LstQuestion.Add(dr.GetString(0));

          }
          vcon.Close();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900