Link to home
Start Free TrialLog in
Avatar of rmk
rmk

asked on

How to calculate the sum of an unbound column in a DataGrid

I'm devloping an on-line voting system and I have a datagrid with the following columns:

CandidateID - boundcolumn and not visible
CandidateName -boundcolumn
NbrOfVotes  - boundcolumn and not visible
VoterNbrOfVotes - unbound templatecolumn as asp:textbox

The user can enter any number of votes for any number of candidates as long as the total number of votes does not exceed a fixed total. I can enter values in the the unbound text box for any number of rows. But when I click the submit button I don't know how to calculate the total number of votes or determine who got how many votes. I can successfully cycle through the Items collection of the datagrid and then cycle through the Cells collection of each DataGridItem, but the unbound column is always empty no matter what I've entered on the page. I don't want the user to have to click an Edit button and enter the number of votes for each candidate that they want to vote for. Since this is my first asp.net.vb application I may be going about this all wrong, so I'd really appreciate any suggestions.
Avatar of tockhoi
tockhoi

Did you try to iterate through the Control property of each Cell?

... Response.Write(dg.Items[1].Cells[0].Controls.Count);

The text that exists in each cell should be wrapped by a Literal control.  Check if the count is greater than 0.
when you perform the button_Click event you can do something like this

Dim index as Integer
Dim count as Integer

For index =0 To DataGrid.Items.Count-1
   Dim tb as TextBox = CType(DataGrid.Items(index).Cells(3).FindControl(the_text_box_Id), TextBox) <- 3 is get from the examle ( the 4th column, the_text_box_Id is the id of you textbox placed in the 4th column
   count = count + int.Parse(tb.Text)
Next

HTH
B..G
Avatar of rmk

ASKER

Here's my page:

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WCOABallot.aspx.vb" Inherits="WCSCOnLineVoting.WCOABallot"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
      <HEAD>
            <title>WCOABallot</title>
            <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
            <meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
            <meta name="vs_defaultClientScript" content="JavaScript">
            <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
      </HEAD>
      <body MS_POSITIONING="GridLayout">
            <form id="Form1" method="post" runat="server">
                  <asp:Table Runat="server" BorderStyle="Solid" BorderWidth="1" BorderColor="Red" id="Table1">
                        <asp:TableRow Runat="server">
                              <asp:TableCell Runat="server" HorizontalAlign="Center">
                                    <b>THE WOODLANDS COMMERCIAL OWNERS ASSOCIATION, INC.</b>
                              </asp:TableCell>
                        </asp:TableRow>
                        <asp:TableRow Runat="server">
                              <asp:TableCell Runat="server" HorizontalAlign="Center">
                                    <b>BOARD OF DIRECTORS ELECTION</b>
                              </asp:TableCell>
                        </asp:TableRow>
                        <asp:TableRow Runat="server">
                              <asp:TableHeaderCell Runat="server">
                                    &nbsp
                              </asp:TableHeaderCell>
                        </asp:TableRow>
                        <asp:TableRow Runat="server">
                              <asp:TableCell Runat="server" HorizontalAlign="Center">
                                    <b>ELECTION OF CLASS A DIRECTOR</b>
                              </asp:TableCell>
                        </asp:TableRow>
                        <asp:TableRow Runat="server">
                              <asp:TableHeaderCell Runat="server">
                                    &nbsp
                              </asp:TableHeaderCell>
                        </asp:TableRow>
                        <asp:TableRow Runat="server">
                              <asp:TableCell Runat="server" HorizontalAlign="Center">
                                    <b>BALLOT</b>
                              </asp:TableCell>
                        </asp:TableRow>
                        <asp:TableRow Runat="server"></asp:TableRow>
                        <asp:TableRow Runat="server">
                              <asp:TableHeaderCell Runat="server">
                                    &nbsp
                              </asp:TableHeaderCell>
                        </asp:TableRow>
                        <asp:TableRow Runat="server"></asp:TableRow>
                        <asp:TableRow Runat="server">
                              <asp:TableCell Runat="server" Width="100%" BorderColor="Green" BorderStyle="Solid">
                                    <asp:DataGrid id="dgrdBallot" runat="server" AutoGenerateColumns="false" Width="100%" HeaderStyle-BorderStyle="Solid"
                                          HeaderStyle-BorderColor="Black" HeaderStyle-BackColor="Green" ItemStyle-BorderStyle="Solid"
                                          ItemStyle-BorderColor="Black" ItemStyle-BorderWidth="1" HeaderStyle-BorderWidth="5" CellPadding="2"
                                          SelectedItemStyle-BackColor="Yellow" GridLines="Both" CellSpacing="2" BorderWidth="1" BorderStyle="Solid"
                                          BorderColor="Olive">
                                          <columns>
                                                <asp:BoundColumn HeaderText="" DataField="CandidateID" visible="False" />
                                                <asp:BoundColumn HeaderText="Vote for one candidate" DataField="CandidateName" />
                                                <asp:BoundColumn HeaderText="" DataField="CandidateVotes" visible="False" />
                                                <asp:templateColumn HeaderText="# Votes" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
                                                      <itemtemplate>
                                                            <asp:textbox runat="server" ID="txtCandidateVotes" Width="50" />
                                                      </itemtemplate>
                                                </asp:templateColumn>
                                          </columns>
                                    </asp:DataGrid>
                              </asp:TableCell>
                        </asp:TableRow>
                        <asp:TableRow Runat="server" Width="100%">
                              <asp:TableCell Runat="server">
                                    Total Entitlement Votes
                              </asp:TableCell>
                              <asp:TableCell Runat="server" Width="50">
                                    <asp:Label Runat="server" ID="lblTotalVotes"></asp:Label>
                              </asp:TableCell>
                        </asp:TableRow>
                  </asp:Table>
                  <asp:Button ID="cmdSubmit" Runat="server" Text="Submit" CommandName="Submit"></asp:Button>
                  <br>
                  <asp:Label ID="lblMessage" Runat="server"></asp:Label>
            </form>
      </body>
</HTML>

Here's the VB code behind:

Public Class WCOABallot
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents dgrdBallot As System.Web.UI.WebControls.DataGrid
    Protected WithEvents Table1 As System.Web.UI.WebControls.Table
    Protected WithEvents lblMessage As System.Web.UI.WebControls.Label
    Protected WithEvents cmdSubmit As System.Web.UI.WebControls.Button

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        If IsPostBack Then
        Else
            Dim tblCandidate As New DataTable("tblCandidate")
            tblCandidate.Columns.Add("CandidateID", System.Type.GetType("System.Int32"))
            tblCandidate.Columns.Add("CandidateName", System.Type.GetType("System.String"))
            tblCandidate.Columns.Add("CandidateVotes", System.Type.GetType("System.Int32"))
            Dim rowCandidate As DataRow
            '
            rowcandidate = tblCandidate.NewRow
            rowCandidate("CandidateID") = 1
            rowCandidate("CandidateName") = "David Kanner, Interstate Terra Development,Inc."
            'rowCandidate("CandidateVotes") = Nothing
            tblCandidate.Rows.Add(rowCandidate)
            '
            rowCandidate = tblCandidate.NewRow
            rowCandidate("CandidateID") = 2
            rowCandidate("CandidateName") = "Steve Sanders, Memorial Hermann Healthcare System"
            'rowCandidate("CandidateVotes") = Nothing
            tblCandidate.Rows.Add(rowCandidate)
            '
            rowCandidate = tblCandidate.NewRow
            rowCandidate("CandidateID") = 3
            rowCandidate("CandidateName") = "Donald R. Willis, Anadarko Petroleum"
            'rowCandidate("CandidateVotes") = Nothing
            tblCandidate.Rows.Add(rowCandidate)
            '
            dgrdBallot.DataSource = tblCandidate.DefaultView
            dgrdBallot.DataBind()
        End If
    End Sub

    Private Sub cmdSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click
        Dim intVotes As Int32
        Dim strVotes As String
        Dim fVotes As Boolean
        Dim item As DataGridItem
        intVotes = 0
        fVotes = False
        lblMessage.Text = ""
        lblMessage.Text = lblMessage.Text & "items=" & dgrdBallot.Items.Count.ToString & "<br>"
        Dim intItem As Int32
        For intItem = 0 To dgrdBallot.Items.Count - 1
            lblMessage.Text = lblMessage.Text & "item#=" & intItem.ToString & "<br>"
            item = dgrdBallot.Items(intItem)
            lblMessage.Text = lblMessage.Text & "cells=" & item.Cells.Count.ToString & "<br>"
            Dim lngCell As Int32
            For lngCell = 0 To item.Cells.Count - 1
                lblMessage.Text = lblMessage.Text & "cell#=" & lngCell.ToString & ";"
                lblMessage.Text = lblMessage.Text & "cellText=" & item.Cells(lngCell).Text.ToString & "<br>"
            Next
        Next intItem
        lblMessage.Text = lblMessage.Text & "<br>done"
    End Sub
End Class

When I run the app and enter 100, 200, 300 as the votes for each candidate and then click the submit button I don't get any values for the number of votes.
ASKER CERTIFIED SOLUTION
Avatar of mmarinov
mmarinov

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Dim dr As DataRow
        Dim decSum As Decimal
        For Each dr In ds.Tables(t).Rows '<-- Change t to the talbe you want (t=0,1,2...)
            ' *** You may wnat to determine what to do whith nulls here
            decSum += Convert.ToDecimal(dr.Item(c)) '<-- Change c to the column you like (0,1,2...)
        Next
        lblSum.Text = Convert.ToString(decSum)