2013-04-16 4 views
3

HimПолучение общих значений определенного столбца от GridView

Я использую ASP.NET/VB.NET с SQL-Server-2012.

У меня аа столбец GridView с 3 полями и поле 1 шаблона, как показано ниже: за

<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 

DataBound()

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 

The последний столбец (поле шаблона) умножает поле количества с поле затрат.

Как рассчитать все значения (путем добавления) в поле шаблона?

+0

вы хотите отобразить сумму в сноске .. – Nag

+0

@Nag если возможно да! – Brian

+0

Добавьте footertemplate и суммируйте значение в ItemTemplate Label на 'grdItems_RowDataBound' – Nag

ответ

0

лично я бы сделал это, выполнив сложение (а также умножение на самом деле) в случае RowDataBound ...

0

Вы должны использовать Databinding события просуммировать значения. См 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

Проведите через все DataRow строки в событии gridview и добавьте значение 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();     

     } 
    } 
+0

Я пробовал, но нижний колонтитул не отображается! – Brian

+0

сделал u установил свойство '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 

от Крейга Льюиса Джонсона из FSSA - Индиана

Смежные вопросы