1,451
社区成员
发帖
与我相关
我的任务
分享
Public Class Good
Public Property Type As String
Public Property Name As String
Public Property Price As Double
Public Property Amount As Double
Public Property Sold As Double
Public Sub New(_type As String, _name As String, _price As Double, _amount As Double, _sold As Double)
Type = _type
Name = _name
Price = _price
Amount = _amount
Sold = _sold
End Sub
End Class
Dim goods As New List(Of Good)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With DataGridView1
.Columns.Add(New DataGridViewTextBoxColumn With
{.DataPropertyName = "Type", .HeaderText = "类型"})
.Columns.Add(New DataGridViewTextBoxColumn With
{.DataPropertyName = "Name", .HeaderText = "名称"})
.Columns.Add(New DataGridViewTextBoxColumn With
{.DataPropertyName = "Price", .HeaderText = "单价"})
.Columns.Add(New DataGridViewTextBoxColumn With
{.DataPropertyName = "Amount", .HeaderText = "库存"})
.Columns.Add(New DataGridViewTextBoxColumn With
{.DataPropertyName = "Sold", .HeaderText = "订购"})
End With
'如果数据源是从数据库查出来的,那就遍历每一行DataRow
'然后生成新的Good对象填充到goods列表,在这里假定数据存在table
'Dim table As New DataTable
'For Each row In table.Rows
' goods.Add(New Good(row("type"), row("name"), row("price"), row("amount"), row("sold")))
'Next
goods.Add(New Good("no1", "货品11", 10.2, 500, 300))
goods.Add(New Good("no1", "货品12", 10.2, 500, 300))
goods.Add(New Good("no2", "货品21", 10.2, 500, 300))
DataGridView1.DataSource = goods
'加载完成以后再绑定事件,防止空对象引用
AddHandler DataGridView1.SelectionChanged, AddressOf DataGridView1_SelectionChanged
End Sub
Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs)
Dim good As Good = CType(DataGridView1.CurrentRow.DataBoundItem, Good)
'可以直接用Ctype转换选中记录为Good对象
MessageBox.Show(
String.Join(vbTab,
{"货名", good.Name, "类型", good.Type, "单价", good.Price,
"库存", good.Amount, "订购", good.Sold}))
End Sub