I have the following code that I use to populate a DataTable with information from a CSV file.
I have declared a DataTable as a class attribute
public partial class Super_Proyectos_LoadProjects: System.Web.UI.Page
{
private DataTable dt;
private DataTable datosC;
string rutaActual;
....
}
protected void btnLoad_Click(object sender, EventArgs e)
{
if(fupCSV.HasFile)
{
try
{
string csvPath = Server.MapPath("~/Projects/") + Path.GetFileName(fupCSV.PostedFile.FileName);
fupCSV.SaveAs(csvPath);
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[8] { new DataColumn("Project ID", typeof(string)), new DataColumn("Worker ID", typeof(string)),
new DataColumn("Project Name", typeof(string)));
dt.TableName = "Project";
string csvData = File.ReadAllText(csvPath);
foreach(string row in csvData.Split('\n'))
{
if(!string.IsNullOrEmpty(row))
{
dt.Rows.Add();
int i = 0;
foreach (string cell in row.Split(','))
{
dt.Rows[dt.Rows.Count - 1][i] = cell;
i++;
}
}
}
gvProyectos.DataSource = dt;
gvProyectos.DataBind();
}
catch(Exception)
{
string script = @"<script type='text/javascript'>
alert('Error al cargar los datos.');
</script>";
ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", script, false);
}
}
}
Everything works fine here
protected void btnAccept_Click(object sender, EventArgs e)
{
Response.Write(dt.Rows[0][0].ToString());
}
But when I click on the accept button I get the following error:
Object reference not set to an instance of an object.
Why do I get error when using the DataTable outside where it was loaded?