Search code examples
c#sql-serverwpftype-conversiondatacolumn

How to convert data type from DataColumn?


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();
        }
    }
}

Solution

  • 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;