HOW TO INTERACT WITH OBJECT IN ANOTHER METHOD USING C#?

F Scott Fitzgerald

Total Post:29

Points:203
Posted by  F Scott Fitzgerald
C# 
C#
 1112  View(s)
Ratings:
Rate this:

I'm populating a self-made Windows Explorer using TreeView & ListView; and I'm currently working on Creating new Folder. What I want to do is when I press the "New Folder" button, a new listView Item would be added with the name "New folder". After that, let users type in the name of the folder by using BeginEdit() method.

private void buttonNewFolder_Click(object sender, EventArgs e)
        {
            ListViewItem newFolder = listView1.Items.Add("New folder", 1);
            newFolder.BeginEdit();
        }
 
 
private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            Directory.CreateDirectory("C:\"+e.Label); //for example
            // Now how can I change some properties of the "newFolder" listView Item in the above methods (buttonNewFolder_Click) ?
        }

In listView1_AfterLabelEdit method, i use Directory.CreateDirectory("C:\"+e.Label); statement to create a new folder. But now, i want to change some properties of the above "newFolder" ListViewItem (for example Tag, ToolTipItem.. - for another use). How can I interact with that ListView Item in buttonNewFolder_Click method ??? Really really hope you guys can help ! Thanks sooo much in advanced !

  1. Babe Zaharias

    Post:19

    Points:133
    Re: How to interact with object in another method using C#?

    newFolder lives within the scope of buttonNewFolder_Click only. Literally move it outside the method to make it more 'globally' accessible:

    ListViewItem newFolder;
     
    private void buttonNewFolder_Click(object sender, EventArgs e)
            {
                newFolder = listView1.Items.Add("New folder", 1);
                newFolder.BeginEdit();
            }
     
     
    private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
            {
                Directory.CreateDirectory("C:\"+e.Label); //for example
                //You now have access to newFolder here
            }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!