操作說明:將自訂資訊新增至 TreeView 或 ListView 控制項 (Windows Forms)
您可以在 Windows Forms TreeView 控制項或控制項中的衍生專案中 ListView 建立衍生節點。 衍生可讓您新增您所需的任何欄位,以及新增自訂方法和建構函式來處理它們。 這項功能的其中一個用途是將 Customer 物件附加至每個樹狀節點或清單項目。 這裡的範例適用于 TreeView 控制項,但相同的方法可用於 ListView 控制項。
衍生樹狀節點
建立衍生自 TreeNode 類別的新節點類別,其具有自訂欄位來記錄檔案路徑。
Class myTreeNode Inherits TreeNode Public FilePath As String Sub New(ByVal fp As String) MyBase.New() FilePath = fp Me.Text = fp.Substring(fp.LastIndexOf("\")) End Sub End Class
class myTreeNode : TreeNode { public string FilePath; public myTreeNode(string fp) { FilePath = fp; this.Text = fp.Substring(fp.LastIndexOf("\\")); } }
ref class myTreeNode : public TreeNode { public: System::String ^ FilePath; myTreeNode(System::String ^ fp) { FilePath = fp; this->Text = fp->Substring(fp->LastIndexOf("\\")); } };
使用衍生樹狀節點
您可以使用新的衍生樹狀節點做為函式呼叫的參數。
在下列範例中,針對文字檔案位置設定的路徑是 [我的文件] 資料夾。 這是因為您可以假設大部分執行 Windows 作業系統的電腦都會包含這個目錄。 也可讓具備最小系統存取層級的使用者安全地執行應用程式。
' You should replace the bold text file ' in the sample below with a text file of your own choosing. TreeView1.Nodes.Add(New myTreeNode (System.Environment.GetFolderPath _ (System.Environment.SpecialFolder.Personal) _ & "\ TextFile.txt ") )
// You should replace the bold text file // in the sample below with a text file of your own choosing. // Note the escape character used (@) when specifying the path. treeView1.Nodes.Add(new myTreeNode(System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal) + @"\TextFile.txt") );
// You should replace the bold text file // in the sample below with a text file of your own choosing. treeView1->Nodes->Add(new myTreeNode(String::Concat( System::Environment::GetFolderPath (System::Environment::SpecialFolder::Personal), "\\TextFile.txt")));
如果您傳遞樹狀節點,且其類型為 TreeNode 類別,則必須轉換成衍生類別。 轉型是物件類型之間的明確轉換。 如需轉換的詳細資訊,請參閱 隱含和明確轉換 (Visual Basic)、 轉換和類型轉換 (Visual C#),或 轉換運算子:() (Visual C++)。
Public Sub TreeView1_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect Dim mynode As myTreeNode mynode = CType(e.node, myTreeNode) MessageBox.Show("Node selected is " & mynode.filepath) End Sub
protected void treeView1_AfterSelect (object sender, System.Windows.Forms.TreeViewEventArgs e) { myTreeNode myNode = (myTreeNode)e.Node; MessageBox.Show("Node selected is " + myNode.FilePath); }
private: System::Void treeView1_AfterSelect(System::Object ^ sender, System::Windows::Forms::TreeViewEventArgs ^ e) { myTreeNode ^ myNode = safe_cast<myTreeNode^>(e->Node); MessageBox::Show(String::Concat("Node selected is ", myNode->FilePath)); }
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應