I'm trying to import an excel sheet into a data table in C#. I keep getting an out of bounds exception because the columns value is being hard coded by me.
for (int c = 0; c <40; c++) { ... }
So rather than hard coding this and having a bunch of empty columns listed on my data table, is there a way to count all the columns being passed in before I create the table? Thereby allowing me to create the table dynamically around the incoming data?
Below is my code.
if (fileUpload.HasFile)
{
DataTable dt = new DataTable();
for (int c = 0; c <40; c++) { dt.Columns.Add(c.ToString(), typeof(string)); }
using (Stream fileStream = fileUpload.PostedFile.InputStream)
using (StreamReader sr = new StreamReader(fileStream))
{
string a = null;
while ((a = sr.ReadLine()) != null)
{
dt.Rows.Add(a.Split(new char[] { ',' }).ToArray());
}
}
GridView1.DataSource = dt;
GridView1.DataBind();