Note that there are some explanatory texts on larger screens.

plurals
  1. POObject reference not set to an instance of an object. (System.NullReferenceException)
    text
    copied!<p>I'm working on my first project outside college. I have a method that should loop through a list and add the elements by parameters to SQL database. The list is populated in another class. When I'm debugging it I get that the value of list is "null", but I use the same list in different class and I get all the items of it. </p> <pre><code>public class AddToDatabase { CopyPDF copyPdf = new CopyPDF(); DBConnection db = new DBConnection(); private List&lt;string&gt; calledList = null; public string error; public void AddPdfToDatabase() { try { string connectionString = db.getTxtContent(); calledList = copyPdf.GetList(); //The GetList method from the other class returns the List I need. using (SqlConnection conn = new SqlConnection(connectionString)) using (DbCommand cmd = conn.CreateCommand()) { cmd.CommandText = "INSERT INTO pdf (Name, Location) VALUES (@names, @locations)"; DbParameter n = cmd.CreateParameter(); DbParameter l = cmd.CreateParameter(); n.ParameterName = "@names"; l.ParameterName = "@locations"; cmd.CommandType = CommandType.Text; conn.Open(); using (DbTransaction tran = conn.BeginTransaction()) { cmd.Transaction = tran; foreach (string line in calledList) //I get the error here { n.Value = line; l.Value = line; cmd.ExecuteNonQuery(); } tran.Commit(); conn.Close(); } } } catch (SqlException ex) { string str; str = "Source:" + ex.Source; str += "\n" + "Number" + ex.Number.ToString(); str += "\n" + "Message" + ex.Message; error = str; } } } </code></pre> <h3>CopyPDF Class :</h3> <pre><code>public class CopyPDF { private List&lt;string&gt; list = null; public void addToList() { //create list list = new List&lt;string&gt;(); //Directory of the PDF files on the network DirectoryInfo dir = new DirectoryInfo(@"W:\"); //get all .PDF files from the given directory FileInfo[] pdffiles = dir.GetFiles("*.pdf"); foreach (FileInfo f in pdffiles) { //remove .pdf, .PDF ending of the strings string yourString = f.Name; string[] remove = {".pdf", ".PDF"}; foreach (string suffix in remove) { if (yourString.EndsWith(suffix)) { yourString = yourString.Remove(yourString.Length - suffix.Length); break; } } //add the string to generic List list.Add(yourString); } } //return the list as PUBLIC so will be accessible from other classes public List&lt;string&gt; GetList() { return list; } //this is the class where I have the GetList(). Thank you for helping </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload