新手问一个关于listview的问题

hbjxx638 2009-03-20 01:43:21
在C++中,CListCtrl有个方法叫SetItemData,这样我就可以把自定义的class和某个item绑定,在C#中的listview有类似的方法吗?或者通过某种方法也可以达到这样的效果
...全文
49 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
david_anwei 2009-03-20
  • 打赏
  • 举报
回复
没有吧!好像只能通过 listView.Items.Add(item) ;
ztenv 2009-03-20
  • 打赏
  • 举报
回复
ListViewItem item;
....
item.tag=对象;
我不懂电脑 2009-03-20
  • 打赏
  • 举报
回复
可以在 Windows 窗体 TreeView 控件中创建派生节点,或在 ListView 控件中创建派生项。派生使您得以添加任何所需的字段,和添加处理这些字段的自定义方法和构造函数。此功能的用途之一是将客户对象附加到每个树节点或列表项。虽然这里的示例是关于 TreeView 控件的,但该方法同样适用于 ListView 控件。

派生树节点
创建一个从 TreeNode 类派生的新节点类,此新节点类具有一个记录文件路径的自定义字段。

Visual Basic 复制代码
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




C# 复制代码
class myTreeNode : TreeNode
{
public string FilePath;

public myTreeNode(string fp)
{
FilePath = fp;
this.Text = fp.Substring(fp.LastIndexOf("\\"));
}
}




C++ 复制代码
ref class myTreeNode : public TreeNode
{
public:
System::String ^ FilePath;

myTreeNode(System::String ^ fp)
{
FilePath = fp;
this->Text = fp->Substring(fp->LastIndexOf("\\"));
}
};



使用派生的树节点
新的派生树节点可用作函数调用的参数。

在下面的示例中,文本文件位置的路径设置是 My Documents 文件夹。这样做是因为假定大多数运行 Windows 操作系统的计算机都包含此目录。这还将允许具有最低系统访问级别的用户安全地运行应用程序。

Visual Basic 复制代码
' 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 ") )




C# 复制代码
// 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") );




C++ 复制代码
// 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)、() 运算符(C# 参考)(Visual C#) 或 Cast Operator: () (Visual C++)。

Visual Basic 复制代码
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




C# 复制代码
protected void treeView1_AfterSelect (object sender,
System.Windows.Forms.TreeViewEventArgs e)
{
myTreeNode myNode = (myTreeNode)e.Node;
MessageBox.Show("Node selected is " + myNode.FilePath);
}


110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧