c# - How to change DataTable type? -


how clone datatable , change column , row type decimal?

private static datatable getdatatabletfromcsvfile(string csv_file_path) {     datatable csvdata = new datatable();     using (textfieldparser csvreader = new textfieldparser(csv_file_path))     {         csvreader.setdelimiters(new string[] { "," });         csvreader.hasfieldsenclosedinquotes = true;         string[] colfields = csvreader.readfields();         foreach (string column in colfields)         {             datacolumn datecolumn = new datacolumn(column);             datecolumn.allowdbnull = true;             csvdata.columns.add(datecolumn);             ;         }         while (!csvreader.endofdata)         {             string[] fielddata = csvreader.readfields();             //making empty value null             (int = 0; < fielddata.length; i++)             {                 if (fielddata[i] == "")                 {                     fielddata[i] = null;                 }             }             csvdata.rows.add(fielddata);         }     }      return csvdata; }  

you have parse strings decimal using decimal.tryparse , use correct column-type. can use datarow.setfield extensions support nullable types:

foreach (string column in colfields) {     datacolumn datacolumn = new datacolumn(column, typeof(decimal));     datacolumn.allowdbnull = true;     csvdata.columns.add(datacolumn); } while (!csvreader.endofdata) {     string[] fielddata = csvreader.readfields();     datarow addedrow = csvdata.rows.add();     (int = 0; < fielddata.length; i++)     {         decimal value;         if(decimal.tryparse(fielddata[i].trim(), out value))             addedrow.setfield<decimal?>(i, value);         else             addedrow.setfield<decimal?>(i, null);     } } 

Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -