Как вычислить значения привязки данных в gridview in ASP.NET-что?
I have created a Databound Gridview with 9 columns. The most of the columns contain money values. I have set 'ShowFooter' to 'True' and have styled my footer however there is currently no data in the footer. What I'm looking to do is calculate the total of all the money columns and put the value within the footer at the bottom of their column - I'm not sure how to go about this so any assistance would be much appreciated. Thank you
Вот HTML-код:
<pre><head runat="server"> <title></title> <style type="text/css"> .auto-style1 { width: 100%; } .auto-style2 { font-size: large; } .auto-style4 { width: 391px; } .auto-style5 { width: 247px; } .auto-style7 { width: 727px; } .auto-style9 { width: 727px; text-align: left; } .auto-style10 { text-align: center; } </style> </head> <body background="Images/mixed-marble_dArc2008.jpg" style="height: 68px"> <form id="form1" runat="server"> <div> <table class="auto-style1"> <tr> <td class="auto-style7"> <asp:Label ID="lblPBO" runat="server" CssClass="auto-style2" Text="Percentile Break Out"></asp:Label> <asp:TextBox ID="TextBoxUSERID" runat="server"></asp:TextBox> <asp:TextBox ID="TextBoxSCENARIO" runat="server"></asp:TextBox> </td> <td> <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSourceDEP" DataTextField="DEPARTMENT" DataValueField="DEPARTMENT" Width="220px" AutoPostBack="True"> </asp:DropDownList> </td> <td> </td> </tr> <tr> <td class="auto-style7"> </td> <td> <asp:SqlDataSource ID="SqlDataSourceDEP" runat="server" ConnectionString="<%$ ConnectionStrings:PERCENTAGE_CALC_DBConnectionString %>" SelectCommand="SELECT DISTINCT [DEPARTMENT] FROM [EMPLOYEE_BASE_DATA]"></asp:SqlDataSource> </td> <td> </td> </tr> <tr> <td class="auto-style9"> <asp:Label ID="lblEmploy" runat="server" Text="Number of Employees"></asp:Label> <asp:Label ID="lblENC" runat="server"></asp:Label> </td> <td> </td> <td> </td> </tr> </table> <br /> <table class="auto-style1"> <tr> <td> <div class="auto-style10"> <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" ShowFooter="True" GridLines="None" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="SqlDataSourceBreakDown" Width="1612px"> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> <Columns> <asp:TemplateField><HeaderTemplate></HeaderTemplate><itemtemplate><%#(Container.DataItemIndex+1)%></itemtemplate></asp:TemplateField> <asp:TemplateField><FooterTemplate>Total</FooterTemplate></asp:TemplateField> <asp:BoundField DataField="BASE_SALARY" DataFormatString="{0:C}" HeaderText="CURRENT BASE" SortExpression="BASE_SALARY" /> <asp:BoundField DataField="SUPPLIMENT" DataFormatString="{0:C}" HeaderText="CURRENT SUPPLIMENT" SortExpression="SUPPLIMENT" /> <asp:BoundField DataField="TOTAL_SALARY" DataFormatString="{0:C}" HeaderText="CURRENT TOTAL" SortExpression="TOTAL_SALARY" /> <asp:BoundField DataField="CURRENT_BASE_PCT" DataFormatString="{0:P0}" HeaderText="CURRENT %" SortExpression="CURRENT_BASE_PCT" /> <asp:BoundField DataField="PROPOSED_X" DataFormatString="{0:C}" HeaderText="PROPOSED BASE" SortExpression="PROPOSED_X" /> <asp:BoundField DataField="Y_SUPPLEMENT" DataFormatString="{0:C}" HeaderText="PROPOSED SUPPLEMENT" SortExpression="Y_SUPPLEMENT" /> <asp:BoundField DataField="TOTAL_COMPENSATION" DataFormatString="{0:C}" HeaderText="PROPOSED TOTAL" SortExpression="TOTAL_COMPENSATION" /> <asp:BoundField DataField="NEW_TOTAL_PCT" DataFormatString="{0:P0}" HeaderText="PROPOSED %" SortExpression="NEW_TOTAL_PCT" /> <asp:BoundField DataField="DEPARTMENT" HeaderText="DEPARTMENT" SortExpression="DEPARTMENT" /> </Columns> <EditRowStyle BackColor="#999999" /> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> <SortedAscendingCellStyle BackColor="#E9E7E2" /> <SortedAscendingHeaderStyle BackColor="#506C8C" /> <SortedDescendingCellStyle BackColor="#FFFDF8" /> <SortedDescendingHeaderStyle BackColor="#6F8DAE" /> </asp:GridView> </div> <asp:SqlDataSource ID="SqlDataSourceBreakDown" runat="server" ConnectionString="<%$ ConnectionStrings:PERCENTAGE_CALC_DBConnectionString %>" SelectCommand="SELECT [BASE_SALARY], [SUPPLIMENT], [TOTAL_SALARY], [CURRENT_BASE_PCT], [PROPOSED_X], [Y_SUPPLEMENT], [TOTAL_COMPENSATION], [NEW_TOTAL_PCT], [DEPARTMENT] FROM [EMPLOYEE_BASE_DATA] WHERE (([DEPARTMENT] = @DEPARTMENT) AND ([SCENARIO] = @SCENARIO) AND ([MATCHED] = @MATCHED))"> <SelectParameters> <asp:ControlParameter ControlID="DropDownList1" Name="DEPARTMENT" PropertyName="SelectedValue" Type="String" /> <asp:ControlParameter ControlID="TextBoxSCENARIO" Name="SCENARIO" PropertyName="Text" Type="String" /> <asp:Parameter DefaultValue="1" Name="MATCHED" Type="String" /> </SelectParameters> </asp:SqlDataSource> </td> <td> </td> </tr> </table> <br /> <br /> <table class="auto-style1"> <tr> <td class="auto-style4"> </td> <td class="auto-style5"> </td> <td> </td> </tr> <tr> <td class="auto-style4"> </td> <td class="auto-style5"> </td> <td> </td> </tr> </table> </div> </form> </body background> </html>
Вот код, стоящий за этим:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Data; using System.Drawing; using System.Data.SqlClient; using System.Configuration; public partial class PercentileBreakOut : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { Bind(); } SqlConnection con99 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["PERCENTAGE_CALC_DBConnectionString"].ConnectionString); con99.Open(); TextBoxUSERID.Text = Session["USER_ID"].ToString(); SqlCommand scmd = new SqlCommand("Select SCENARIO from EMPLOYEE_BASE_DATA where SCENARIO = '" + TextBoxUSERID.Text + "'", con99); SqlDataReader dr = scmd.ExecuteReader(); if (dr.Read()) { TextBoxSCENARIO.Text = dr["SCENARIO"].ToString(); } dr.Close(); con99.Close(); SqlConnection con11 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["PERCENTAGE_CALC_DBConnectionString"].ConnectionString); con11.Open(); SqlCommand scmd11 = new SqlCommand("Select count(MATCHED) from EMPLOYEE_BASE_DATA where MATCHED = '1' AND SCENARIO = '" + TextBoxSCENARIO.Text + "'", con11); object count = scmd11.ExecuteScalar(); lblENC.Text = count.ToString(); con11.Close(); } private void Bind() { this.GridView1.DataBind(); } //int total = 0; protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e) { //int sum = Convert.ToInt32("SUM(BASE_SALARY)"); if (e.Row.RowType == DataControlRowType.DataRow) { total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "CURRENT BASE")); } if (e.Row.RowType == DataControlRowType.Footer) { Label lblamount = (Label)e.Row.FindControl("lblTotal"); //lblamount.Text = "Total Value is : " + total.ToString(); } } }
Что я уже пробовал:
Я пробовал другие коды, но они добавляют таблицу данных, и ничего не работает.
Richard Deeming
SqlCommand scmd = new SqlCommand("Select SCENARIO from EMPLOYEE_BASE_DATA where SCENARIO = '" + TextBoxUSERID.Text + "'", con99); SqlCommand scmd11 = new SqlCommand("Select count(MATCHED) from EMPLOYEE_BASE_DATA where MATCHED = '1' AND SCENARIO = '" + TextBoxSCENARIO.Text + "'", con11);
Не делай этого так!
Ваш код уязвим для SQL-инъекция[^]. НИКОГДА используйте конкатенацию строк для построения SQL-запроса. ВСЕГДА используйте параметризованный запрос.
Все, что вы хотели знать о SQL-инъекции (но боялись спросить) | Трой Хант[^]
Как я могу объяснить SQL-инъекцию без технического жаргона? | Обмен Стеками Информационной Безопасности[^]
Шпаргалка по параметризации запросов | OWASP[^]
Computer Wiz99
Спасибо за часть SQL-инъекции. Вы знаете, как помочь мне с моей проблемой под рукой?
Maciej Los
Мой виртуальный 5!
Computer Wiz99
Простите, что?
Maciej Los
Это означает, что комментарий Ричарда очень хорош и содержит много ценных замечаний.
Computer Wiz99
Ладно, спасибо. Я понимаю, как вы показали мне, но будет ли это работать для Gridview, который заполняется из базы данных?
Maciej Los
Да, это так. Вам нужно внести некоторые изменения в код, который я вам показал.