Click here to Skip to main content
15,888,158 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'll me honest: its a ridiculous problem, I've spent more than hour because those 4 lines of code, but I cant think clearly, dont know if its because its 5550 am...

C#
cmd = new SqlCommand("Select Texto FROM Notes WHERE ID_users='" + id_user.ToString() + "'", conn);
          SqlDataReader dr = cmd.ExecuteReader();
          int num = 9; // static variable to change later
          string[] texto = new string[num];
         
               while (dr.Read())
               {
                   for (int i = 0; i < num; i++)
                   {
                       texto[i] = dr[0].ToString();
                   }
               }


So the problem is, the result from that SQL statement its simple 9 different strings. And I want to store them in Array - texto.

But for some (obvious) reason, all fields from array gets the same (the last result from sql query).

Can you please help me?
Posted

Hi Maxxdd,

You are using nested loop here that is the problem. Remove for loop from there and declare i before while loop and increment i after assignment.
 
Share this answer
 
Comments
Maxdd 7 23-Dec-10 0:36am    
it worked like a charm. thank you so much :)
Maxdd 7 23-Dec-10 0:36am    
for (i = 0; i < num; )
{
while (dr.Read())
{
texto[i] = dr[0].ToString();
i++;
}

}
C#
int i;
i=0;                     
                while (dr.Read())
                {
                  texto[i] = Convert.ToString(dr[0]);
                  i++;
                }


Used convert.ToString Beacuse if the string in dr[0] in null it will not through an exception otherwise it througs null pointer exception
 
Share this answer
 
C#
for (int i = 0; i <= dr.RecordsAffected - 1; i++) {
    texto[i] = dr(0);
}


one more thing i would like to add is to use sql parameters to prevent sql injections :

for example:

cmd = new SqlCommand("Select Texto FROM Notes WHERE ID_users=@Iduser, conn);

C#
SqlParameter param = new SqlParameter();
param.ParameterName = "@Iduser";
param.Value = id_user.ToString();
param.Size = 15;
param.SqlDbType = System.Data.SqlDbType.VarChar;

cmd.Parameters.Add(param);


Cheers!
 
Share this answer
 
Comments
fjdiewornncalwe 24-Dec-10 12:41pm    
@Tarun: Good answer, but one suggestion that I give to devs in code reviews all the time. Keep statements as simple as possible. Where you write "i <= dr.RecordsAffected -1", it would be more efficient and easier to read if you just put "i < dr.RecordsAffected". It is a very minor thing, but cycles add up quickly if dr.RecordsAffected is very large. (This is really also just a hint to the OP. As a new dev this is something I would encourage him to pick up early)

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