如何在ListView的User ID列旁添加ImageList中的图标?
在ListView中添加图标的完整解决方案
我来帮你搞定这个问题!要在ListView里显示你ImageList中的.ico图标,只需要完成两个关键步骤,结合你已有的代码,我给你详细说明:
1. 将ImageList与ListView关联起来
首先得让ListView知道要使用哪个ImageList里的图标,你可以通过代码或者设计界面来完成:
代码方式(推荐在窗体加载时执行)
假设你的ImageList控件名叫imgListStudents,直接把它绑定到ListView的图标集合:
' 绑定小图标(适合详细视图/列表视图) lvwStudent.SmallImageList = imgListStudents ' 如果要显示大图标(大图标视图),就用下面这句 ' lvwStudent.LargeImageList = imgListStudents
设计界面方式
在Visual Studio的属性窗口里找到你的ListView控件,找到SmallImageList或LargeImageList属性,下拉选择你的ImageList即可。
2. 添加带图标的列表项
因为你的ImageList里只有一个图标,它的索引是0(ImageList的项索引从0开始计数)。在创建ListViewItem的时候,把这个索引作为构造函数的第二个参数传入就行:
我给你补充一个填充列表项的方法,和你已有的列头方法配合使用:
Private Sub filllvwStudentItems() ' 先清空现有项,避免重复添加 lvwStudent.Items.Clear() ' 示例:添加一条学生数据,同时指定图标索引0 Dim newStudentItem As New ListViewItem("U001", 0) ' 添加子项对应列头 newStudentItem.SubItems.Add("Doe") newStudentItem.SubItems.Add("Jane") newStudentItem.SubItems.Add("M") ' 将项添加到ListView lvwStudent.Items.Add(newStudentItem) ' 可以继续添加更多学生项,同样用索引0即可 End Sub
3. 整合到你的初始化流程里
在窗体加载事件里,按顺序执行这些操作:
Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' 先添加列头 filllvwStudentColumnHeaders() ' 关联ImageList lvwStudent.SmallImageList = imgListStudents ' 填充带图标的学生项 filllvwStudentItems() End Sub
额外说明
如果之后你在ImageList里添加了更多图标,只需要把对应图标在ImageList里的索引传给ListViewItem的构造函数就行(比如第二个图标用1,第三个用2,以此类推)。
内容的提问来源于stack exchange,提问作者Сашко Мицевски
相关产品推荐
相关产品推荐

