行也有Name属性的哦
多数时候,ListView的数据来自DataTable,前面我们已经看到,在生成ListViewRow的时候,可以将其Tag属性设置为对应的DataRow,这样在ListView的事件中,我们可以轻松获得某个ListViewRow对应的DataRow,但是反过来,要知道某个DataRow对应的ListViewRow,则不太容易,往往遍历所有的ListViewRow,逐行比较才行。
但是行有Name属性,我们可以在生成ListViewRow的时候,将DataRow的主键值复制给行的Name属性,例如:
Dim
lvw As
WinForm.ListView
= e.Form.Controls("ListView1")
lvw.View
= ViewMode.Details
Dim
cls()
As
String
=
{"编号","姓名","部门","职务","性别","地址"}
'定义列名
For
i
As
Integer
=
0
To
cls.Length
-
1
'增加列
Dim
c
As
WinForm.ListViewColumn
=
lvw.Columns.Add()
c.Text
=
cls(i)
'指定列标题
c.Name
=
cls(i)
'指定列名
Next
For
Each
dr
As
DataRow
In
DataTables("员工").DataRows
'从数据表中提取数据
Dim vr
As WinForm.ListViewRow
= lvw.Rows.Add()
'增加一行
For Each
cl As
String In
cls
'逐列取值
vr(cl)
= dr(cl)
Next
vr.Tag
= dr
'将DataRow赋值给ListViewRow的Tag属性
vr.Name
= dr("_Identify")
''将DataRow的主键赋值给ListViewRow的Name属性
Next
lvw.ResumeRedraw()
'恢复绘制
这样我们随时获取DataRow对应的ListViewRow,例如:
Dim
lv As
WinForm.ListView
= e.Form.Controls("ListView1")
Dim
id As
String = Tables("员工").Current("_Identify")
Dim
vr As
WinForm.ListViewRow
= lv.Rows(id)
vr.Delete()
一些用户可能会这样编写代码:
Dim
lv As
WinForm.ListView
= e.Form.Controls("ListView1")
Dim
vr As
WinForm.ListViewRow
= lv.Rows(Tables("员工").Current("_Identify"))
这样是不行的,因为_Identify等主键列通常是整数型,假定主键列的值是10,那么上面的代码得到的是第11行(编号从0开始),而不是名称为“10”的行,这种错误不易发现,我自己就经常犯,大家务必要记住:需要根据行的名称获取行时,传递过去的参数必须是字符型,而不是整数型,如果主键是整数型,必须先将主键值转换为字符型再传递:
Dim
lv As
WinForm.ListView
= e.Form.Controls("ListView1")
Dim
id As
String = Tables("员工").Current("_Identify")
Dim
vr As
WinForm.ListViewRow
= lv.Rows(id)