Gab
Gab

Reputation: 45

How to sum one column in gridview and show it in a textbox

     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

I have this code for my gridview, I want to total all the units and show it on my textbox;txtTotalUnits Thanks.This is my gridview and textbox

Upvotes: 1

Views: 1064

Answers (3)

SSS
SSS

Reputation: 5393

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

Upvotes: 0

alainlompo
alainlompo

Reputation: 4434

You could add an event handler for the GridView.RowDataBound Event as follows

Dim total as Integer

Sub CustomersGridView_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles CustomersGridView.RowDataBound

    If e.Row.RowType = DataControlRowType.DataRow Then

      total = total + Convert.ToInt32(e.Row.Cells(the_column_index).Text) .
      txtTotalUnits.Text = Convert.ToString(total)

    End If

  End Sub

More similar examples on MSDN

Upvotes: 1

mybirthname
mybirthname

Reputation: 18127

Use the datasource table, you need using System.Linq;

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

txtTotalUnits.Text = result.ToString(); 

Upvotes: 0

Related Questions