如何在gridview中对一列进行求和并将其显示在文本框中

时间:2016-11-16 22:25:40

标签: asp.net vb.net gridview

     Protected Sub Page_Load(ByVal sender As Object, ByVal e As        System.EventArgs) Handles Me.Load
        If Not Me.IsPostBack Then
        Dim constr As String = ConfigurationManager.ConnectionStrings("mcbdatabseConnectionString").ConnectionString
        Using con As New MySqlConnection(constr)
            Using cmd As New MySqlCommand("SELECT * FROM mcbdatabse.subject_enrolled")
                Using sda As New MySqlDataAdapter()
                    cmd.Connection = con
                    sda.SelectCommand = cmd
                    Using dt As New DataTable()
                        sda.Fill(dt)
                        GridView1.DataSource = dt
                        GridView1.DataBind()
                    End Using
                End Using
            End Using
        End Using
     End If
End Sub

我的gridview有这个代码,我希望将所有单位合计并在我的文本框中显示; txtTotalUnits谢谢。This is my gridview and textbox

3 个答案:

答案 0 :(得分:1)

您可以为 GridView.RowDataBound 事件添加事件处理程序,如下所示

en

MSDN

上的更多类似示例

答案 1 :(得分:0)

使用数据源表,您需要using System.Linq;

var result = tbl.AsEnumerable().
                 Sum(x => Convert.ToDecimal(x["ColumnNameForWhichYouWantSum"].ToString()));

txtTotalUnits.Text = result.ToString(); 

答案 2 :(得分:0)

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  If Not Me.IsPostBack Then
    Dim constr As String = ConfigurationManager.ConnectionStrings("mcbdatabseConnectionString").ConnectionString
    Using con As New MySqlConnection(constr)
      Using cmd As New MySqlCommand("SELECT * FROM mcbdatabse.subject_enrolled")
        Using sda As New MySqlDataAdapter()
          cmd.Connection = con
          sda.SelectCommand = cmd                    
          Using dt As New DataTable()
            sda.Fill(dt)
            Dim total As Integer = 0
            For i As Integer = 0 To dt.Rows.Count - 1
              Dim drw As DataRow = dt.Rows(i)
              Dim units As Integer = CInt(drw("Units")) 'Assuming Units is the column name'
              total += units
            Next i
            txtTotalUnits.Text = total.ToString
            GridView1.DataSource = dt
            GridView1.DataBind()       
          End Using
        End Using
      End Using
    End Using
  End If
End Sub