簡體   English   中英

如何使用vb.net添加Gridview單元?

[英]How to add the Gridview cells using vb.net?

我的Gridview有以下字段

ID          Product            Price ($)
1           Pencil             1
2           Pen                1
3           Rubber             2

我想在Gridview頁腳中計算價格字段的總價格。

總價格= 4

使用VB.NET怎么做?

Sub BindAmount()
    Dim r As DataGridViewRow

    If DataGridView1.RowCount > 0 Then
        Dim TAmt As Decimal = 0.0

        For Each r In DataGridView1.Rows
            If r.Visible = True Then
                TAmt = TAmt + r.Cells("PRICE").Value
                TXT_PRICE.Text = TAmt
            End If
        Next
    Else
         TXT_PRICE.Text = 0
    End If
End Sub

**按鍵加載

使用dataTable的計算方法獲取所有價格的總和,並處理RowDataBound事件以設置頁腳的文本:

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindData()
        End If
    End Sub

    Private Sub BindData()
        Dim tbl As New DataTable
        Dim col As New DataColumn("ID", GetType(Int32))
        tbl.Columns.Add(col)
        col = New DataColumn("Product", GetType(String))
        tbl.Columns.Add(col)
        col = New DataColumn("Price", GetType(Double))
        tbl.Columns.Add(col)
        Dim row As DataRow = tbl.NewRow
        row("ID") = 1
        row("Product") = "Pencil"
        row("Price") = 1
        tbl.Rows.Add(row)
        row = tbl.NewRow
        row("ID") = 1
        row("Product") = "Pen"
        row("Price") = 1
        tbl.Rows.Add(row)
        row = tbl.NewRow
        row("ID") = 1
        row("Product") = "Rubber"
        row("Price") = 2
        tbl.Rows.Add(row)
        Me.GridView1.ShowFooter = True
        Me.GridView1.DataSource = tbl
        Me.GridView1.DataBind()
    End Sub

    Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.Footer Then
            Dim tbl As DataTable = DirectCast(GridView1.DataSource, DataTable)
            Dim total As Double = DirectCast(tbl.Compute("SUM(Price)", Nothing), Double)
            e.Row.Cells(2).Text = total.ToString
        End If
    End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM