Error adding data to datatable: column 1 cannot be found
The code is as follows:
StreamReader sr = new StreamReader(fs, encoding); string strLine = ""; string[] DataLine = null; dt.Columns.Add(new DataColumn()); while ((strLine = sr.ReadLine()) != null) { DataLine = strLine.Split(','); DataRow dr = dt.NewRow(); for (int i = 0; i < DataLine.Length; i++) { dr[i] = DataLine[i]; } dt.Rows.Add(dr); }
Reason: data columns must be created before adding data rows, but the appropriate columns cannot be initialized because the number of columns is uncertain. In this way, each row is written into the DataTable as a string, so that a column can be created.
StreamReader sr = new StreamReader(fs, encoding); string strLine = ""; dt.Columns.Add(new DataColumn()); while ((strLine = sr.ReadLine()) != null) { DataRow dr = dt.NewRow(); dr[0] = strLine; dt.Rows.Add(dr); }
A compromise solution to this problem.
Similar Posts:
- This Row already belongs to another table error when trying to add rows?
- Python pandas merge cannot merge two data frames based on column names (Key Error)?
- [How to Solve] SQLite database error: no such column
- Python Pandas: Read_Excel() and to_Excel() function
- MySQL database insert into statement with parameters Error
- How to Solve Datatable field value is empty Error
- [Solved] PostgreSQL configure: error: readline library not found
- [Solved] MySQL uses the workbench tool, and the table status is read only
- [Solved] HttpClient HttpRequestHeaders.From Error: The specified value is not a valid ‘From’ header string.
- [Solved] EF An error occurred while updating the entries. See the inner exception for details.