from DataReader to double[] array (asp.net20 c#)

W

Web learner

At line unitsInStock.Add((double)dr.GetValue(1)); I get same error:
Specified cast is not valid

If you comment out above code line and also Response.Write(unitsInStock[0]);
then the code works fine. That means it works for productName array.

My purpose is to populate an array from SqlDataReader as below:

double[] unitsInStock = { 120, 104, 112, 111 };
string[] productName = { "Boysenberry", "Something", "Another item", "Demo
item" };

Thanks in advance

Novice

--------------------------------------------

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="System.Collections.Generic" %>
<script language="c#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
SqlConnection objConnection = new
SqlConnection("server=(local)\\SQLEXPRESS; database=Northwind; integrated
security=true;");
String strSQL = "SELECT productName, unitsInStock FROM Products
WHERE unitsInStock >= 100";
SqlCommand objCommand = new SqlCommand(strSQL, objConnection);
objConnection.Open();

SqlDataReader dr = objCommand.ExecuteReader();

List<string> productName = new List<string>();
List<double> unitsInStock = new List<double>();

while (dr.Read())
{
productName.Add((string)dr.GetValue(0)); //No Error
unitsInStock.Add((double)dr.GetValue(1)); //ERROR : Specified
cast is not valid
}
dr.Close();
objConnection.Close();

Response.Write(productName[0]);
Response.Write(unitsInStock[0]);
}
</script>
 
G

Guest

Hey Web learner,

In Northwind database UnitsInStock is defined as smallint. You can't
directly cast it to .NET double type. You can either change your List's type
or cast it two times. Here are both approaches:

Approach 1:
-------------
List<string> productName = new List<string>();
List<Int16> unitsInStock = new List<Int16>();

while (dr.Read())
{
productName.Add((string)dr.GetValue(0)); //No Error
unitsInStock.Add((Int16)dr.GetValue(1)); //No Error here too ;-)
}

Or try Approach 2:
---------------------
List<string> productName = new List<string>();
List<Double> unitsInStock = new List<Double>();

while (dr.Read())
{
productName.Add((string)dr.GetValue(0)); //No Error
unitsInStock.Add((double)(Int16)dr.GetValue(1)); //No Error here too ;-)
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top