Title: [ASP.NET][DataGrid] DataGird 給予序號 (一般版)
<asp:DataGrid id="dgAddOrderID" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 56px"
runat="server" CellPadding="4" BackColor="White" BorderWidth="1px"
BorderStyle="None" BorderColor="#3366CC" Height="20px" Width="512px" AutoGenerateColumns="False"
ShowFooter="True" PageSize="3" AllowPaging="True">
<FooterStyle ForeColor="#003399" BackColor="#99CCCC"></FooterStyle>
<SelectedItemStyle Font-Bold="True" ForeColor="#CCFF99" BackColor="#009999"></SelectedItemStyle>
<ItemStyle ForeColor="#003399" BackColor="White"></ItemStyle>
<HeaderStyle Font-Bold="True" ForeColor="#CCCCFF" BackColor="#003399"></HeaderStyle>
<Columns>
<asp:BoundColumn HeaderText="序號"></asp:BoundColumn>
<asp:BoundColumn DataField="LastName" HeaderText="名字"></asp:BoundColumn>
<asp:BoundColumn DataField="FirstName" HeaderText="姓氏"></asp:BoundColumn>
<asp:BoundColumn DataField="BirthDate" HeaderText="日期" DataFormatString="{0:yyyy-MM-dd}"></asp:BoundColumn>
<asp:BoundColumn DataField="City" HeaderText="成市"></asp:BoundColumn>
</Columns>
<PagerStyle HorizontalAlign="Left" ForeColor="#003399" BackColor="#99CCCC" Mode="NumericPages"></PagerStyle>
</asp:DataGrid>
.cs
//資料繫節時處理的事件就是ItemDataBound()
private void AddOrderID(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
//如果當前資料不為空
if(e.Item.ItemIndex != -1 )
{
//取的當前索引項值+1,因為索引項值是以0開始的
int orderID = e.Item.ItemIndex+1;
//設定第一列的單元格用目前得索引值+1
e.Item.Cells[0].Text = OrderID.ToString();
}
}