【问题标题】:How to add the Gridview cells using vb.net?如何使用 vb.net 添加 Gridview 单元格?
【发布时间】:2011-01-26 12:55:44
【问题描述】:

我的 Gridview 有以下字段

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

我想计算Gridview Footer中价格字段的总价...即..

总价 = 4

如何使用 VB.NET 做到这一点?

【问题讨论】:

    标签: asp.net vb.net visual-studio-2008 gridview


    【解决方案1】:
    【解决方案2】:

    使用dataTable的compute方法获取所有价格的总和并处理RowDataBound事件来设置Footer的文本:

     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
    

    【讨论】:

      【解决方案3】:
      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
      

      **按下键加载

      【讨论】:

      • 这是怎么回事?这究竟是什么?你能解释一下你的答案吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 1970-01-01
      • 2020-10-17
      相关资源
      最近更新 更多