假设我有一个名字,电话,电子邮件和一个叫selected的bool的个人类。这些人是通过分号分隔的文本文件生成的。我循环文件并获取每个人的值。在DataGridView中使用"use“(选中的复选框)、”名称“和”电子邮件“显示它们的最佳实践是什么?(请注意,我不接电话了)现在,我在Person类中有一个名为MakeDataGridRow的函数,我使用这样的函数:
For each line blah blah StreamReader(filename) blah...
Dim P as New Person(line.split(";"))
MyDataGridview.Rows.Add(P.MakeDataGridRow)
End For这是可行的,但这并不是很好,因为当我想对列表做一些事情时,我必须循环列表并为每个选中的行生成一个新的人,对吗?在这种情况下,我无法得到电话号码,因为它不在名单上。我可以将它们保存在一个人列表中(在文件读取循环中),并根据这个列表检查每一行以获得电话,但我不喜欢这个解决方案。
最好的解决方案是Person类继承DataGridViewRow,以便当我循环我的行时,我可以使用已创建好的Person来检查电话号码。我该怎么做?
一些事情,比如:
Public Class Person
Inherits DataGridViewRow
Public Name As String
Public Telephone as String
Public Email As String
Public Selected As Boolean
Public Sub New(ByVal Values As String())
Name = Values(0)
Telephone = Values(1)
Email = Values(2)
Selected = True
End Sub
End Class如何在DataGridView中将该类显示为一行,以便以后在与人员一起执行某些操作时,可以执行更类似的操作
For Each P as Person In MyDataGridView.Rows
If P.Selected Then
MsgBox(P.Name & ", telephone: " & P.Telephone)
End If
End For我想你明白我想要达到的目标,有什么建议吗?
发布于 2014-08-22 12:44:45
不,把它们看作是两个独立的物体。不要从DataGridViewRow继承Person类。
将Inherits DataGridViewRow从Person类定义中删除。
在Person类中,将所有字段转换为属性。根据您使用的.net版本,将Property关键字添加到声明中就足够了,或者您可能需要放置完整的属性定义。
现在,它可以很容易地被数据库到网格。(可以指定固定列。我只是在这个例子中自动生成)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' create a new list of Persons. THis will act as datasource for the gridview.
Dim personsList As New List(Of Person)
' fill data into the list.
' *I skip the implementation of this part, you already have that code*
' bind the persons list to the Grid view.
DataGridView1.AutoGenerateColumns = True
DataGridView1.DataSource = personsList
' hide unwanted columns
DataGridView1.Columns("Email").Visible = False
End Sub现在你可以很容易地得到你的个人对象和任何东西。例如,要获得电话号码:
Private Function GetPhoneNumber(ByVal rowNumber As Integer) As String
Return DirectCast(DataGridView1.Rows(rowNumber).DataBoundItem, Person).Telephone
End Function 发布于 2014-08-22 12:32:41
继承DataGridViewRow并不能给您带来任何真正的好处。我认为最好的解决方案是创建一个List of Person,其中包含您从CSV文件中获得的所有数据。
然后将列表绑定到DataGridView,如下所示
MyDataGridView.BindingSource = MyListPersons当您想要显示您的数字时,只需循环所选的行,使用CType获取底层对象( Person对象)并显示您的手机。
这会将dgv行转换为Person对象。
Dim p As Person = CType(row.DataBoundItem, Person)
If p IsNot Nothing Then
MsgBox(p.Name & ", telephone: " & p.Telephone)
End Ifhttps://stackoverflow.com/questions/25446681
复制相似问题