2013-04-16 4 views
3

그놈GridView에서 특정 열의 총 값 가져 오기

SQL-Server-2012와 함께 ASP.NET/VB.NET을 사용하고 있습니다.

<asp:GridView ID="grdItems" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource3" Font-Names="Tahoma" ForeColor="#333333" GridLines="None"> 
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> 
    <Columns> 
     <asp:BoundField DataField="item_name" HeaderText="Item" SortExpression="item_name" /> 
     <asp:BoundField DataField="item_cost" HeaderText="Cost (inc. VAT)" SortExpression="item_cost" /> 
     <asp:BoundField DataField="item_quantity" HeaderText="Quantity" SortExpression="item_quantity" /> 
     <asp:TemplateField HeaderText="Sub-Total (inc. VAT)"> 
      <ItemTemplate> 
       <asp:Label ID="TextBox3" runat="server" Text='<%# Convert.ToInt32(Eval("item_quantity")) * Convert.ToDouble(Eval("item_cost"))%>'></asp:Label> 
      </ItemTemplate> 
     </asp:TemplateField> 
     <asp:TemplateField> 
      <FooterTemplate> 
       <asp:Label ID="lblTotalPrice" runat="server" /> 
      </FooterTemplate>     
     </asp:TemplateField> 
    </Columns> 
    <EditRowStyle BackColor="#999999" /> 
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" VerticalAlign="Middle" /> 
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> 
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Center" VerticalAlign="Middle" /> 
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> 
    <SortedAscendingCellStyle BackColor="#E9E7E2" /> 
    <SortedAscendingHeaderStyle BackColor="#506C8C" /> 
    <SortedDescendingCellStyle BackColor="#FFFDF8" /> 
    <SortedDescendingHeaderStyle BackColor="#6F8DAE" /> 
</asp:GridView> 

코드 뒤에 :

Imports System.Data.SqlClient 
Imports System.Data 

Partial Class ProjectReport 
    Inherits System.Web.UI.Page 

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load 

     Dim ProjectID = Session("project_id") 
     Session("ProjectID") = ProjectID 

    End Sub 
    Protected Sub grdItems_RowDataBound(sender As Object, e As GridViewRowEventArgs) 

     Dim totalPrice As Decimal = 0 

     If e.Row.RowType = DataControlRowType.DataRow Then 


      Dim lblPrice As Label = DirectCast(e.Row.FindControl("lblTotalPrice"), Label) 

      Dim price As Decimal = [Decimal].Parse(lblPrice.Text) 


      totalPrice += price 

     End If 

     If e.Row.RowType = DataControlRowType.Footer Then 
      Dim lblTotalPrice As Label = DirectCast(e.Row.FindControl("lblTotalPrice"), Label) 

      lblTotalPrice.Text = totalPrice.ToString() 


     End If 
    End Sub 


End Class 

바인딩()

Private Sub BindData() 

     Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True") 
     Dim query As New SqlCommand("SELECT Items.item_name, Items.item_cost, project_items.item_quantity FROM Items INNER JOIN project_items ON items.item_id = project_items.item_id WHERE project_items.project_id = @parameter", conn) 

     query.Parameters.AddWithValue("@UserID", Session("ProjectID")) 

     Dim da As New SqlDataAdapter(query, conn) 

     da.SelectCommand = query 

     Dim table As New DataTable() 




     da.Fill(table) 

     grdItems.DataSource = table 
     grdItems.DataBind() 
    End Sub 

을 다음과 같이

나는 3 개 필드와 1 템플릿 필드 AA의 GridView 열이 마지막 열 (템플릿 필드)은 수량 필드에 비용 필드.

템플릿 필드에 (추가하여) 모든 값을 어떻게 계산합니까?

+0

당신이 바닥 글에 .. – Nag

+0

@Nag의 합계를 표시 할 할 가능하다면 예! – Brian

+0

footeremplate을 추가하고 ItemTemplate의 값을 합계합니다.'grdItems_RowDataBound'에 – Nag

답변

0

나는 개인적으로 RowDataBound 이벤트에 추가 (물론 실제로 곱셈)을 수행하여 그것을 할 것 ...

0

당신은 값 합계를 데이터 바인딩 이벤트를 사용해야합니다. this example를 확인하고 사용자의 요구에 적응 :

private Decimal OrderTotal; 

protected void GridView1_DataBinding(object sender, EventArgs e) 
{ 
    OrderTotal = 0.0M; 
} 

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     //Keep adding the subtotal here 
     OrderTotal += Subtotal;    
    } 
} 

protected void GridView1_DataBound(object sender, EventArgs e) 
{  
    //Set a control with the total sum 
    LabelOrderTotal.Text = OrderTotal.ToString("C"); 
} 

은 기본적으로 당신은 RowDataBound 경우에 당신은 총합에 레이블을 설정 DataBound 이벤트의 값을 계속 추가. 또는 DataBound 이벤트에서 그리드를 반복하고 모든 것을 추가 할 수 있습니다.

+0

안녕하세요, 저는이 튜토리얼을 사용하지 않아도됩니다. 나는 새로운 코드를 업데이트 할 것이다. 감사. – Brian

+0

@Brian DataBound 이벤트가 누락되었습니다. 신중하게 예제를 읽으십시오 – nmat

+0

업데이트 된 코드를 참조하십시오. '쿼리'에서 SqlCommand를 문자열로 변환 할 수 없다는 오류가 나타납니다. – Brian

0

gridview DataBound 이벤트의 모든 DataRow 행을 반복하고 실행중인 총 변수에 TextBox3 값을 추가하십시오.

Protected Sub grdItems_DataBound(ByVal sender as Object, ByVal e as EventArgs) 
    Dim row As GridViewRow = Nothing 
    Dim runningTotal As Double = 0.0 
    For i As Integer = 0 to grdItems.Rows.Count 
     row = grdItems.Rows(i) 
     If row.RowType = DataControlRowType.DataRow Then 
      ' Add error handling here 
      runningTotal += Ctype(CType(row.FindControl("TextBox3"), Label).Text, Double) 
     End If 
    Next i 
End Sub 
0

당신이 시도 할 수 있습니다 ...

decimal totalScore=0; 
protected void gd__RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      Label TextBox3= (Label)e.Row.FindControl("TextBox3");       

      decimal points = Decimal.Parse(TextBox3.Text);    

      totalScore += points;    
         } 
     if (e.Row.RowType == DataControlRowType.Footer) 
     { 
      Label lblTotal = (Label)e.Row.FindControl("lblTotal"); 
      lblTotal.Text = totalScore.ToString();     

     } 
    } 
FSSA에서 크레이그 루이스 존슨
+0

시도했지만 바닥 글이 표시되지 않습니다. – Brian

+0

격자에 'showfooter = true' 속성을 설정 했습니까? – Nag

0
  <asp:TemplateField HeaderText="first_name" SortExpression="first_name"> 
      <EditItemTemplate> 
      <asp:TextBox ID="TextBox_first_name" runat="server" Text='<%# Bind("first_name") %>'></asp:TextBox> 
      </EditItemTemplate> 
      <ItemTemplate> 
      <asp:Label ID="Label_first_name" runat="server" Text='<%# Bind("first_name") %>'></asp:Label>  
      </ItemTemplate> 
      </asp:TemplateField> 

      <asp:TemplateField HeaderText="middle_name" SortExpression="middle_name"> 
      <EditItemTemplate> 
      <asp:TextBox ID="TextBox_middle_name" runat="server" Text='<%# Bind("middle_name") %>'></asp:TextBox> 
      </EditItemTemplate> 
      <ItemTemplate> 
      <asp:Label ID="Label_middle_name" runat="server" Text='<%# Bind("middle_name") %>'></asp:Label> 
      </ItemTemplate> 
      </asp:TemplateField> 

      <asp:TemplateField HeaderText="last_name" SortExpression="last_name"> 
      <EditItemTemplate> 
      <asp:TextBox ID="TextBox_last_name" runat="server" Text='<%# Bind("last_name") %>'></asp:TextBox> 
      </EditItemTemplate> 
      <ItemTemplate> 
      <asp:Label ID="Label_last_name" runat="server" Text='<%# Bind("last_name") %>'></asp:Label> 
      </ItemTemplate> 


Protected Sub GridView_clients_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GridView_clients.RowCommand 

    If e.CommandName = "Select" Then 

     Dim index As Integer = Convert.ToInt32(e.CommandArgument) 'gets the row 

     '........................................ 

     Dim client_first_name As String = DirectCast(GridView_clients.Rows(index).FindControl("Label_first_name"), Label).Text.ToString 
     Dim client_middle_name As String = DirectCast(GridView_clients.Rows(index).FindControl("Label_middle_name"), Label).Text.ToString 
     Dim client_last_name As String = DirectCast(GridView_clients.Rows(index).FindControl("Label_last_name"), Label).Text.ToString 


     'MsgBox(client_first_name) 
     'MsgBox(client_middle_name) 
     'MsgBox(client_last_name) 

     lb_test.Text = client_first_name & " " & client_middle_name & " " & client_last_name 

    End If 

End Sub 

- 인디애나

관련 문제