GridView 使用GridViewRow

使用GridView來完成訂單之小計、合計

大家好!

我是一位職場新鮮人。

我想將我的學習結果與各位分享,

並非以教授為前提,

若各位前輩對我的程式有覺得不妥的,

歡迎批評指教,相信這樣我才能有進步的空間。

 

在此分享我寫訂單時,將商品數量 * 單價 =小計,

最後在GridView內加入一列(GridViewRow)總計。

 我拉了一個SqlDataSource 和一個GridView。

小計方面,我是直接在Select 資料庫的時候,多Select一個欄位名total ,

他是從我資料庫內num欄位 * price欄位。

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
            SelectCommand="SELECT *,num*price as total FROM [test]"></asp:SqlDataSource>
        
        
        </div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#CCCCCC"
            BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2"
            DataKeyNames="id" DataSourceID="SqlDataSource1" ForeColor="Black" OnDataBound="GridView1_DataBound">
            <FooterStyle BackColor="#CCCCCC" />
            <RowStyle BackColor="White" />
            <Columns>
                <asp:BoundField DataField="id" HeaderText="編號" ReadOnly="True" SortExpression="id" />
                <asp:BoundField DataField="a" HeaderText="品名" SortExpression="a" />
                <asp:BoundField DataField="num" HeaderText="數量" SortExpression="num" />
                <asp:BoundField DataField="price" HeaderText="價格" SortExpression="price" />
                <asp:BoundField DataField="total" HeaderText="小計" ReadOnly="True" SortExpression="total" />
            </Columns>
            <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
        </asp:GridView>

接著,在GridView1_DataBound寫入

 

01 protected void GridView1_DataBound(object sender, EventArgs e)
02     {
03         
04         GridViewRow GVR = new GridViewRow(0, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
05         TableCell tc_0 = new TableCell();
06         tc_0.ColumnSpan = 4;
07         tc_0.HorizontalAlign = HorizontalAlign.Center;
08         tc_0.Text = "總計";
09         GVR.Cells.Add(tc_0);
10         Int32 sum = 0;
11         for (Int32 i = 0; i < GridView1.Rows.Count; i++)
12         {
13             sum += Int32.Parse(GridView1.Rows[i].Cells[4].Text);
14         }

15         TableCell tc_1 = new TableCell();
16         tc_1.Text = sum.ToString();
17         GVR.Cells.Add(tc_1);
18
19         //將GridViewRow寫入GridView1內
20         GridView1.Controls[0].Controls.AddAt(GridView1.Rows.Count + 1, GVR);
21     }

結果為