views:

40

answers:

1

i want to know what is the wrong in this query I want to select all rows for 1 column

 string command = "select money from User_Data";
 SqlCommand update_money = new SqlCommand(command, con_string.con);
 SqlDataReader money_reader;
 money_reader = update_money.ExecuteReader();
+2  A: 

You're on the right track - now once you have the data reader, you need to iterate over the rows:

string command = "select money from User_Data";

SqlCommand update_money = new SqlCommand(command, con_string.con);
SqlDataReader money_reader = update_money.ExecuteReader();

List<decimal> _allValues = new List<decimal>();

while(money_reader.Read())
{
    _allValues.Add(money_reader.GetDecimal(0));
}

This assumes your money column would be of type decimal(x,y) or money on SQL Server.

marc_s
i do it but when I wrote decimal moneyValue = money_reader.GetMoney(1);I got exception handle ( out of index ) although the table has 2 rows !!!!
salamonti
@salamonti Because the GetMoney(ordinal) function where ordinal is the column index, not the row index. Ordinal corresponds to the index of the field in your select statement, the the index of the row in your result set.
Wil P
ok how can I correct it ?
salamonti
@salamonti: sorry, my bad - the method is called `.GetDecimal()` - not GetMoney as I falsely used.... and yes - the number in the GetDecimal method is the index of **the column** you wish to read - since you only have a single column in your SQL statement, that column index has to be 0 all the time.
marc_s
ok Now how to save all records in the column in list ?
salamonti
@salamonti: updated my answer
marc_s
thanks so much it worked
salamonti