Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding to a list from within method

Tags:

c#

asp.net

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.

like image 961
sevenaxl Avatar asked Dec 11 '25 19:12

sevenaxl


1 Answers

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.

like image 148
Jonathon Chase Avatar answered Dec 13 '25 07:12

Jonathon Chase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!