>string sDescrip=""; >string sValue=""; >DataTable dt = new DataTable(); >DataRow dr; > >// add two columns >dt.Columns.Add(new DataColumn("Description", typeof(String))); >dt.Columns.Add(new DataColumn("Value", typeof(double))); >// I have a foreach() loop here to work through another DataTable >// and decide if want want to extract info from it for the grid (complex reasons) >// say the condition is: iWantItCondition (for each item) >if (iWantItCondition==true) >{ >// oRow[oColumn.Columname] is the current row in the current column in the source table > > // we move here to a column to get decription -- [code snipped] > sDescrip=oRow[oColumn.ColumnName].ToString(); > > // we move here to another column to get value -- [code snipped] > sValue=oRow[oColumn.ColumnName].ToString(); > dr = dt.NewRow(); > dr[0] = sDescrip; > > // here's the problem > // I want to format the string depending on what it is (sometimes a percentage, sometimes currency) > // for example's simplicity let's deal only with Currency here > > // this line doesn't work: > // Runtime error: "Input string was not in a correct format. > // Couldn't store <$134.00> in Value Column. Expected type is Double." > dr[1] = double.Parse(sValue).ToString("C") > > ////// debug: this line works and it shows onscreen as $134.00 correctly > Response.Write(sValue + ": " + double.Parse(sValue).ToString("C") + "<br>"); > ////// debug > > dt.Rows.Add(dr); >} > >// after done building the datarows, bind them to a grid >this.GridViewOthers.DataSource = dt; >this.GridViewOthers.DataBind(); >>Why does the Response.Write work fine with proper Currency formatting, but the assignment to data row 2nd column dr[1] does not? dr[1] is defined as a double. The formatted value I want to store is parsed as a double.
// Your line below explicitly says that the Value column stores Doubles: dt.Columns.Add(new DataColumn("Value", typeof(double))); // You give no idea what sValue is. I suspect that the result type of the following is not double: dr[1] = double.Parse(sValue).ToString("C"); // so I'm guessing the compiler complaint is bang-on. // Note in your original code you left off the trailing semi-colon - I assume that's a typo here // and not in your actual code // I also suspect the Response.Write call is working because it's either treating it as a string // concatenation, or maybe Response.Write has enough overloads to successfully write "any old junk" // to the screen (sorta like, IIRC, the VB6 MessageBox). // I've run into a couple of similar cases where I couldn't figure out why what I thought was // an explicit type conversion wouldn't work. In those cases I resorted to System.Convert. // Assuming svalue can be meaningfully converted to a double, you could try dr[1] = Convert.ToDouble( sValue );