L. Havrlisan L. Havrlisan - 24 days ago 11
SQL Question

Retrieve more data from a SQL Server database

I'm taking 2 variables from SQL table 'Zupanije', but I don't know how to use them. I tried the code below but it takes the key twice, instead of key and value.

sqlCmd.CommandText = "SELECT COUNT(*) From Zupanije";
conn.Open();
int count = (int)sqlCmd.ExecuteScalar();
conn.Close();

sqlCmd.CommandText = "SELECT Naziv, Sifra From Zupanije";
conn.Open();
using (var zupanijeReader = sqlCmd.ExecuteReader())
{
while (zupanijeReader.Read())
{
for (int i=0; i <= count; i++)
{
izborZupanija.Add(zupanijeReader[i].ToString(),
Convert.ToDouble(zupanijeReader[i]));
}
}
}
conn.Close();

gsd gsd
Answer

I agree with @leetibbett. The SqlDataReader will iterate over each result when you call Read(). You then pull out each column value use the SqlDataReader.GetString and SqlDataReader.GetDouble methods, passing in the column index as an argument.

sqlCmd.CommandText = "SELECT Naziv, Sifra From Zupanije";
conn.Open();
using (var zupanijeReader = sqlCmd.ExecuteReader())
{
    while (zupanijeReader.Read())
    {
        izborZupanija.Add(zupanijeReader.GetString(0), zupanijeReader.GetDouble(1));
    }
}
conn.Close();