sevenaxl
sevenaxl

Reputation: 33

adding to a list from within method

I am new to Asp.net and C#, I am trying to log changes made to a directory. The problem I am running into is that from within my method which picks up changes made to a directory, I am unable to add the information (in the form of a string) to a list, listbox, or anything outside the method at all.

Here is the method that picks up directory changes:

protected void OnChanged(object sender, FileSystemEventArgs e)
{

    if (!m_bDirty)
    {

        m_Sb.Clear();

        m_Sb.Append(e.FullPath);
        m_Sb.Append(" ");
        m_Sb.Append(e.ChangeType.ToString());
        m_Sb.Append("    ");
        m_Sb.Append(DateTime.Now.ToString());
        m_bDirty = true;
        test.Add(m_Sb.ToString());

Here are my variables outside the method:

public partial class _Default : System.Web.UI.Page
{
private System.IO.FileSystemWatcher watcher;
private bool m_bDirty;
private StringBuilder m_Sb = new StringBuilder();
private List<String> test = new List<String>();

My problem is that when I try to pull information from the list(test) outside the OnChanged method, there is nothing there.

Upvotes: 3

Views: 78

Answers (1)

Jonathon Chase
Jonathon Chase

Reputation: 9704

Whenever a postback occurs on the page, your List test will be reinitialized as a new List, which will clear any data it may have had.

You can instead declare it as a static field, then initialize it during a page

private static List<string> test;

protected void Page_Init(object sender, EventArgs e) {
    test = test ?? new List<string>();
    // ... additional initalization
}

You can then clear the list by setting it back to null after it's handled by your other method.

Upvotes: 3

Related Questions