Pregunta

I have the following code and want to get to know how to get the DataColumn row[col] to float?

queryString = "SELECT Price FROM sampledata";

SqlCommand cmd = new SqlCommand(queryString, connection);

SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("SampleTable");

sda.Fill(dt);

foreach (DataRow row in dt.Rows)
{
    // this value should become float pPrice = 0;
    string pPrice = "";

    foreach (DataColumn col in dt.Columns)
    {
        if (col.ToString().Trim() == "Price")
        {
            // pPrice = float.Parse(row[col].ToString()) does not work
            // table column from sampledata is float
            pPrice = row[col].ToString();
        }
    }
}
¿Fue útil?

Solución

Try instead of

pPrice = row[col].ToString();

this

float value = (float)row[col];

You are explicitly setting your value to an string, so you cannot assign a float to it.

Also, be shure the column is a float and not a double/decimal, an easy way to know is

Type t = row[col].GetType();
string typeName = t.Name;

Otros consejos

If you want to get/fetch list of float column's from data table then you have to Travers a loop of each data table column and check below code.

if(dt.Columns[0].GetType() == float) {

}

Convert.ToSingle() can be used for conversion in float.

MSDN Reference 1

MSDN Reference 2

float pPrice = Convert.ToSingle(row[col]);

Or

float pPrice = Single.Parse(row[col].ToString());
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top