Search code examples
c#treeview

I C# treeView shows folder sequence nodes How to rename nodes Recurrently on form load without changing source folder name


I have form showing treeview that treeview preview some folders, subfolders and files from the hard drive like the following example :

TreeView

how to change the names of the nodes in the treeview without changing the source folder name

I mean that I need to change the node name just in the form for example, a node named "debug" show to the user like "XXX" but the folder still named debug


Solution

  • First of all, I can't tell if you are using Windows Forms or WPF, so I'm going to explain it for Windows Forms.


    Make a ContextMenuStrip, then make a DropdownItem with the text being Rename

    Next, double-click the item; this will open the Form.cs of the Form containing the TreeView

    Now, make a new form, by clicking the Project button, which is located in the top-bar of Visual Studio, (Which I assume you are using) and click Add Windows Form - This will open a window asking what name the Form should be.

    Next, after adding the new form, create a TextBox on the new Form, and a Button, with the text being Rename

    Okay, now that we've covered that part, go back to the Form.cs and navigate to the rename_Click() event. (I'm sure that the event name isn't actually rename_Click(), it's just an example)

    Now, put this code in between the curly brackets(Code Block):

    renameForm rf = new renameForm();
    rf.ShowDialog();
    

    OKAY! Now, we need to head back to the other Form we created earlier. Open the Form.cs of the earlier created Form, and scroll to the top. Before the public Form() event, type:

    public static string newName = "";
    

    So! When the parent Form that contains our ContextMenuStrip and TreeView opens our second Form

    But, now, we will need to send data back, right?

    Go back to the rename_Click() in the parent Form, the one that contains our TreeView and ContextMenuStrip, and before the rf.ShowDialog();, add:

    rf.FormClosed += rename_Closed;
    

    you may need to press TAB to create the event if it does not already exist

    In the second Form, containing our TextBox and Button, double-click the Button, and open the Form.cs

    Inside of the curly brackets(Code Block) of the button_Click(), add:

     newName = textBox1.Text;
    

    Then, inside of the curly brackets(Code Block) of rename_Closed(), add:

    treeView1.SelectedNode.Text = renameForm.newName;
    

    This should create a simple, but effective rename system.


    Hope it helps you :)