How can I convert a value given by a DataRow cell to double?
Loading
How can I convert a value given by a DataRow cell to double?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jayraj ChhayaRank #304 · 8.2K reputationPosted Sep 26, 2025, 7:52 AM EDT
double value = Convert.ToDouble(row["ColumnName"]);(or
row.Field("ColumnName") if the column is already numeric).Tuhin PaulRank #7 · 71.9K reputationPosted Sep 26, 2025, 12:05 PM EDT
You can convert a DataRow cell value to double using several methods. Using
Convert.ToDouble()DataRow row = dataTable.Rows[0]; double value = Convert.ToDouble(row["ColumnName"]);This method handles
nullvalues (converts to0.0) and works with various numeric types.You can also use
double.TryParse()DataRow row = dataTable.Rows[0]; object cellValue = row["ColumnName"]; if (double.TryParse(cellValue?.ToString(), out double value)) { // Use 'value' here - conversion was successful Console.WriteLine($"Converted value: {value}"); } else { // Handle conversion failure Console.WriteLine("Could not convert to double"); // You might want to use a default value value = 0.0; // or whatever default makes sense }Choose the method that best fits your data certainty and error handling requirements!
Sandhiya PriyaRank #26 · 43.2K reputationPosted Oct 13, 2025, 2:55 AM EDT
To convert a value from a
DataRowcell to adoublein C#,you have a few safe options depending on whether the value can be
nullor might not be convertible. Here’s a detailed guide:1. Using
Convert.ToDoublePros: Handles
nullandDBNull.Valueby throwing an exception.Cons: Will throw if the value is
nullor not numeric.Example with null check:
2. Using
double.TryParseThis is safer if the data might be a string or may fail conversion.
double value; bool success = double.TryParse(row["ColumnName"]?.ToString(), out value); if (success) { Console.WriteLine("Value: " + value); } else { value = 0; // default }Pros: Won’t throw exceptions.
Cons: Needs extra handling if
null.3. Using casting (if you’re sure the type is numeric)
Only works if the underlying type is already
double. Will throwInvalidCastExceptionif it isn’t.Best Practice
If you’re dealing with a database column that might contain
NULLor string numeric values: