此範例是示範如何在 GridView 加入一個自動編號的欄位,以標示該資料列的編號。
首先在 GridView 第一欄加入一個 TemplateField,並在 TemplateField 的 ItemTemplate 加入一個 Label (ID=lblNo),asxp 對應程式碼如下。
01 | <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" |
02 | DataKeyNames="Flag,ID" DataSourceID="SqlDataSource1" EmptyDataText="沒有資料錄可顯示。"> |
04 | <asp:TemplateField HeaderText="序號"> |
06 | <asp:Label ID="lblNo" runat="server" Text="Label"></asp:Label> |
08 | <ItemStyle Wrap="True" /> |
09 | <HeaderStyle Wrap="False" /> |
然後在 GridView 的 RowDataBound 事件中,設定每一列的 lblNo 的 Text 屬性值為 RowIndex+1。
因為 RowIndex 起始編號為 0 ,故每列的自動編號為 RowIndex+1。
1 | Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound |
3 | If e.Row.RowType = DataControlRowType.DataRow Then |
4 | oLabel = CType(e.Row.Cells(0).FindControl("lblNo"), Label) |
5 | oLabel.Text = (e.Row.RowIndex + 1).ToString() |
以上的寫法遇到 GridView 分頁時,都是由 1 開始編號,若需分頁需要接續編號,可改用修改如下。
01 | Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound |
03 | Dim oGridView As GridView |
05 | If e.Row.RowType = DataControlRowType.DataRow Then |
06 | oGridView = CType(sender, GridView) |
07 | oLabel = CType(e.Row.Cells(0).FindControl("lblNo"), Label) |
08 | oLabel.Text = (oGridView.PageIndex * oGridView.PageSize) + (e.Row.RowIndex + 1).ToString() |
沒有留言:
張貼留言