Home SqlDataReader returns empty
Reply: 1

SqlDataReader returns empty

Alicja Krzeszowiec
1#
Alicja Krzeszowiec Published in 2018-01-12 13:57:13Z

Here's my code:

static void Main(string[] args)
        {
            SqlConnection _sqlConnection = new SqlConnection (@"Data Source=(local)\SQLEXPRESS;Integrated Security=SSPI;" + "Initial Catalog=OnlineBanking");
            _sqlConnection.Open();
            var cmdSelect = new SqlCommand("Select * from BankAccounts where AccountId = 1", _sqlConnection);
            using (SqlDataReader dataReader = cmdSelect.ExecuteReader())
            {
                if (dataReader.HasRows)
                {
                    dataReader.Read();
                    float AccountBalance = (float)dataReader["Balance"];
                    Console.WriteLine("{0}", AccountBalance);
                }
            }

This line

 float AccountBalance = (float)dataReader["Balance"];

causes problems, as dataReader returns empty. How can I fix it? What's the issue?

Marc Gravell
2#
Marc Gravell Reply to 2018-01-12 14:11:53Z

System.InvalidCastException (comments) is not "empty" - it is an invalid cast. So presumably the data isn't a float; it could be double, or - and I suspect this is the case: decimal. Note that decimal is a much better choice for numbers that represent money.

So: find out which it is, and use the correct cast. I suspect that this will work:

decimal accountBalance = (decimal)dataReader["Balance"];
Console.WriteLine("{0}", accountBalance);

You can also use the various methods on Convert to be more forgiving, i.e.

decimal accountBalance = Convert.ToDecimal(dataReader["Balance"]);
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.291779 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO