17526

Get Numeric Value from DataGridViewCell?

Question:

I'm trying to retrieve numeric values from a DataGridView. So far, the only way I've found is to retrieve them as a string and convert them to numeric.

Convert.ToDouble(MyGrid.SelectedRows[0].Cells[0].Value.ToString());

There must be an easier way. The cell is originally populated from a DataSet with a numeric field value but since the DataGridViewCell object returns it as an object, I can't do a straight assignment. I must be missing something simple here.

Thanks.

Answer1:

I've actually just recently dealt with this problem and TryParse I think is your best bet with respect to robustness, but don't forget to check if the value in the Cell is null, if so TryParse will fail and throw up an error.

double d = 0; if(grid[col,row].Value != null) double.TryParse(grid[col,row].Value.ToString(), out d);

I would also recommend avoiding a straight cast, unless you know absolutely what type you are converting and that there will, in fact, be a value there, it will probably at some point cause an error in your code.

Answer2:

With DataGridViewCell you can just cast the .Value to your known type; the following is a complete example that shows this happening (using double) from a DataTable (like your example). Additionally, Convert.To{blah}(...) and Convert.ChangeType(...) might be helpful.

using System.Data; using System.Windows.Forms; static class Program { static void Main() { Application.EnableVisualStyles(); DataTable table = new DataTable { Columns = { {"Foo", typeof(double)}, {"Bar", typeof(string)} }, Rows = { {123.45, "abc"}, {678.90, "def"} } }; Form form = new Form(); DataGridView grid = new DataGridView { Dock = DockStyle.Fill, DataSource = table}; form.Controls.Add(grid); grid.CurrentCellChanged += delegate { form.Text = string.Format("{0}: {1}", grid.CurrentCell.Value.GetType(), grid.CurrentCell.Value); if (grid.CurrentCell.Value is double) { double val = (double)grid.CurrentCell.Value; form.Text += " is a double: " + val; } }; Application.Run(form); } }

Answer3:

DataGridViewCell has ValueType property. You can use to do directly cast the value to that type without first converting it to string:

if(MyGrid.SelectedRows[0].Cells[0].ValueType!=null && MyGrid.SelectedRows[0].Cells[0].ValueType == Double) return (Double)MyGrid.SelectedRows[0].Cells[0].Value;

Answer4:

What is the error you are getting? Convert.ToDouble has an overloaded method that takes an object, so you shouldn't need the ToString()? Unless you are doing a TryParse?

Answer5:

Since DataGridViewCell.Value is an Object type, you really need to convert it to the appropriate type, Double or any numeric type in your case. The DataGridView contents aren't strongly typed so you have to cast the values retrieved from its cells.

Recommend

  • CVS Bridge to SVN
  • How to store (and use) the current mouse position?
  • Insert multiple lines of text before specific line using Bash
  • Interactions between Expert Advisor and Indicators on MQL4
  • Compare a column between 2 csv files and write differences using Python
  • How to get the relative position of a Dictionary element?
  • href inside href [duplicate]
  • How to discover a file is changed in GIT during a push
  • C: Custom strlen() library function
  • C++ accessing vector
  • How to start server for Selenium grid Java Maven setup
  • How to format data from string variable
  • Allocating a 2D contiguous array within a function
  • How to override jQuery promise callback
  • Iterate twice through a DataReader
  • Why does Sencha 2 only work in Webkit browsers?
  • Regex for nested values
  • multidatatrigger with multibinding in ControlTemplate.Triggers
  • Dynamically load css stylesheet and wait for it to load
  • VBA Excel, loop through variables
  • converter json to two dimensional array
  • Cloud Code function running twice
  • gspread or such: help me get cell coordinates (not value)
  • Thread safety of a fluent like class using clone() and non final fields
  • Converting a WriteableBitmap image ToArray in UWP
  • Use of this Javascript
  • Linq Objects Group By & Sum
  • align graphs with different xlab
  • How to format a variable of double type
  • Linker errors when using intrinsic function via function pointer
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Buffer size for converting unsigned long to string
  • Hits per day in Google Big Query
  • how does django model after text[] in postgresql [duplicate]
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • LevelDB C iterator
  • Linking SubReports Without LinkChild/LinkMaster
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • How can i traverse a binary tree from right to left in java?
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize