0

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?

Bassie
  • 9,529
  • 8
  • 68
  • 159
Luis
  • 65
  • 7
  • Debug the code and you will see that somewhere along the line you are calling a function on a null-valued object (probably the value stored at `dt.Rows[0][0]`) – Bassie May 07 '17 at 22:46
  • Why are you putting it in a DataTable in the first place? Why aren't you putting it into a strongly typed object? Why are you using fields in your page, and expecting them to persist through postbacks? (hint, they won't) – mason May 07 '17 at 23:53
  • weird, I just answered another version of this question about an hour ago – Keith Nicholas May 08 '17 at 00:02
  • Thanks for answering. Hi @mason Can you explain why I can not use fields? What is the correct way to do it? Thank you – Luis May 08 '17 at 00:14
  • Fields (otherwise known as instance variables) are specific to that instance of the class, in this case, `Super_Proyectos_LoadProjects` which is your page class. Each request to the server results in a new instance of your page class, so all instance variables are discarded. When you click a button or otherwise trigger a server side event from your ASP.NET page, it results in a new postback, which is a new HTTP request. So `dt` doesn't persist between postbacks. What you should do is load the data into a strongly typed model (create a new class instead of using DataTable) – mason May 08 '17 at 00:20
  • ..and then store an instance of that class in some storage such as ViewState, hidden form field, a cookie or in the database. For example, you'd have a class `public Project { public string Id {get; set;} public string Name {get; set;} public string WorkerId {get; set;} }` and then a list of all the projects that you read in from the CSV file, `List` and then you would persist that list. – mason May 08 '17 at 00:22
  • Wow, what a bad thing I'm doing. Thanks so much for the explanation. – Luis May 08 '17 at 00:26

0 Answers0