c# - Ignore the comma inside a row from a csv -
this question has answer here:
- dealing commas in csv file 21 answers
- parsing csv comma in data [duplicate] 3 answers
so here issue.
i reading csv datagridview. first row of csv column headers , of file becomes row. reading file , using datasource of datagridview. lines in csv have similar to
name,test,1,2,3,test,2,3,2,1,test,name
where bolded above when use .split() considers new cell in row number of columns 10 instead of 11 , following error:
input array longer number of columns in table
how can around this.
below c# code.
openfiledialog openfile = new openfiledialog(); openfile.initialdirectory = "c:\\"; openfile.filter = "txt files (*.txt)|*.txt| csv files (*.csv) | *.csv| files (*.*) | *.*"; openfile.filterindex = 2; openfile.restoredirectory = true; try { if (openfile.showdialog() == dialogresult.ok) { string file = openfile.filename; streamreader sr = new streamreader(file); /* gets lines of csv */ string[] str = file.readalllines(file); /* creates data table*/ datatable dt = new datatable(); /* gets column headers first line*/ string[] temp = str[0].split(','); /* creates columns of gridview base on stored in temp array */ foreach (string t in temp) { dt.columns.add(t, typeof(string)); } /* retrieves rows after first row , adds datatable */ (int = 1; < str.length; i++) { string[] t = str[i].split(','); dt.rows.add(t); } /* assigns data grid view data source based on stored in dt */ datagridview1.datasource = dt; } } catch (exception ex) { messagebox.show("error: csv selected not loaded" + ex.message); }
this sounds more data issue programming issue. if csv file supposed have 10 columns yet have 11, how know 1 column?
one thing check number of columns before adding row.
for (int = 1; < str.length; i++) { string[] t = str[i].split(','); if(t.length == temp.length) dt.rows.add(t); }
Comments
Post a Comment