ASP .Net Repeater 控制項與Bootstrap table 整合應用

在本文中, 我們示範如何透過ASP .Net的Repeater控制項產出HTML table, 並使用Bootstrap 對table 的支援客製化table的外觀.

示範中所採用的資料來自於北風(Northwind)資料庫中對Orders及Order Details資料表的查詢,查詢指令如下:

select O.OrderID, sum(D.UnitPrice*D.Quantity) as 'Total' from [Orders] as O
join [Order Details] as D on O.OrderID = D.OrderID Group By O.OrderId

如下圖



1. 首先我們準備一個新的網頁, 該網頁套用了有整合Bootsrtap的主版負面, 過程可參見
在Visual Studio ASP .Net空白網站範本中加入Bootstrap (Part 1)

2. 接下來在網頁中加入如下圖的HTML

     <div>
        <table class="table">
            <caption><strong>Northwind Sales</strong></caption>
            <thead>
                <th>Order ID</th><th>Total</th>
            </thead>
            <tbody>
               
            </tbody>
        </table>
    </div>


3. 然後在<tbody></tbody>中加入Repeater 控制項, 如下所示

               <asp:Repeater ID="rpSales" runat="server">
                    <HeaderTemplate></HeaderTemplate>
                    <ItemTemplate>
                        <tr class="">
                            <td>
                                <%# Eval("OrderID") %>
                            </td>
                            <td>
                                 <%# Eval("Total") %>
                            </td>
                        </tr>
                    </ItemTemplate>
                </asp:Repeater>



4. 然後在Page Load 事件中使用ADO .Net 查詢資料, 程式碼如下

            DataSet ds = new DataSet();
            string strConn = ConfigurationManager.AppSettings["NorthwindDB"];
            SqlConnection Conn = new SqlConnection(strConn);
            SqlCommand Cmd = new SqlCommand();
            Cmd.Connection = Conn;
            Cmd.CommandType = CommandType.Text;
            Cmd.CommandText ="select O.OrderID, sum(D.UnitPrice*D.Quantity) as 'Total'  from "  +
                " [Orders] as O join [Order Details] as D on O.OrderID = D.OrderID  Group By .OrderId";
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = Cmd;
            da.Fill(ds);
            rpSales.DataSource = ds;
            rpSales.DataBind();



5.加入下列setClass方法 於Page Load事件下

      protected string setClass(double _totals)
        {
            string classToApply = string.Empty;
            if (_totals >= 2000.0)
            {
                classToApply = "success";
            }
            else if ((_totals < 1000.0) && (_totals >= 500.0)) {
                classToApply = "warning";
            }
            else if (_totals < 500.0)
            {
                classToApply = "danger";
            }
            return classToApply;
        }

如金額超過2000, 標示class="success". 如金額在1000以下500以上則標示class="warning". 如金額在500以下則標示class="danger".


6. 在Repeater 控制項內<tr></tr>中加入

                      class="<%# setClass(Convert.ToDouble(Eval("Total"))) %>"

如下圖

7. 測試可見如下畫面



現在畫面中的HTML table會自動依據金額標示顏色.


留言