简体   繁体   中英

c# - How to interact with object in another method?

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 !

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
        }

IMPORTANT: It's a real possibiliy that (depending on the order in which these events are fired/methods are called) newFolde r may be null. Do your necessary checks, code as defensively as possible when accessing newFolder in either method, now that it can be accessed at many more points throughout the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM