DataRow Write Data Error: column 0 or column 1 cannot be found

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: