使用Sub将行添加到DataGrid

时间:2014-05-27 22:50:55

标签: vb.net datagrid

我是vb.net的新手

所以我尝试做的是向数据网格添加行。我已经能够通过添加以下内容来实现这一目标:

Public Class X

 Public Sub Button_Click(sender As Object, e As RoutedEventArgs)
    InitializeComponent()
    Dim items As New List(Of reportLine)()
    listview1.ColumnWidth = New DataGridLength(240)
    items.Add(New reportLine() With {.Items = "Total Project Funding", .Amount = 42.0})
    items.Add(New reportLine() With {.Items = "Sammy Doe", .Amount = 7})
    items.Add(New reportLine() With {.Items = "Sammy Doe", .Amount = 7})
    items.Add(New reportLine() With {.Items = "Sammy Doe", .Amount = 7})
    items.Add(New reportLine() With {.Items = "Sammy Doe", .Amount = 99})
    datagrid1.ItemsSource = items
End Sub
Private Sub rptLine(ByRef rptItem As String, ByRef rptAmount As Double)
    Dim items As New List(Of reportLine)()
    items.Add(New reportLine() With {.Items = rptItem, .Amount = rptAmount})
    datagrid1.ItemsSource = items
End Sub

End Class

Public Class reportLine
  Public Property Items() As String

  Public Property Amount() As Integer

End Class

我想要做的是能够在按钮点击事件中添加一行,如下所示

rptLine("Report Line", 450)
rptLine("Report Line", 450)
rptLine("Report Line", 450)

我意识到每次调用它时,rptLine Sub都会创建一个新的Itemsource实例。我已经尝试了很多方法来解决这个问题,并且每个方面都有障碍。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您使用的是ListView吗?

Private Sub rptLine(ByRef rptItem As String, ByRef rptAmount As Double)
    Dim listItem As ListViewItem = ListView1.Items.Add(rptItem)
    listItem.Subitems.Add(rptAmount)
End Sub

您使用的是DataGridView吗?

Private Sub rptLine(ByRef rptItem As String, ByRef rptAmount As Double)
    Dim row As DataGridViewRow = DataGridView1.Rows(DataGridView1.Rows.Add())
    With row
        .Cells(column1Name.Name).Value = rptItems
        .Cells(column2Name.Name).Value = rptAmount
    End With
End Sub

你可能会进一步简化这些,但这应该给你基本的想法。