I'm trying to get data from a SQL Server local database. I have created Table with 1 columns buyEURrate type float and the table name is CurrencyRates I have global double variable and I'm trying to set its value the same as the first Row from the buyEURrate columns in CurrencyRates on FormLoad so this code below is inside FormLoad. I'm really new to SQL with C#.
I'm using Visual Studio 2012 and the this is Windows Forms App
using (SqlCeConnection conn =
new SqlCeConnection(@"Data Source=C:\Users\FluksikartoN\Documents\Visual Studio 2012\Projects\BuroFoki\BuroFoki\MainDB.sdf"))
using (SqlCeCommand cmd = conn.CreateCommand())
{
conn.Open();
//commands represent a query or a stored procedure
cmd.CommandText = "SELECT buyEURrate FROM CurrencyRates";
using (SqlCeDataReader rd = cmd.ExecuteReader())
{
while (rd.Read())
{
EURbuy = Convert.ToDouble(rd[0]);
EURsell = Convert.ToDouble(rd[1]);
//Index was outside the bounds of the array. error
}Table
}
conn.Close();
}
SOmething like this should work:
using (SqlCeConnection conn =
new SqlCeConnection(@"Data Source=C:\Users\FluksikartoN\Documents\Visual Studio 2012\Projects\BuroFoki\BuroFoki\MainDB.sdf"))
using (SqlCeCommand cmd = conn.CreateCommand())
{
conn.Open();
//commands represent a query or a stored procedure
cmd.CommandText = "SELECT buyEURrate FROM CurrencyRates";
using (SqlCeDataReader rd = cmd.ExecuteReader())
{
while(rd.Read())
{
double variable = Convert.ToDouble(rd[0]);
string foo = rd.GetString[1];
//do something with variable and foo before going to next row in query
}
}
conn.Close();
}
This may also work
double variable = rd.GetDouble(0);
Although I'm not 100% sure GetDouble is an actual function like GetString() is
Edit
After double checking double variable = rd.GetDouble(0)
will work to pull the first column data as a double