日期:2012-09-20  浏览次数:21138 次

在DataGrid的第一列自动生成序号,如下图:

    代码实现:

前台(WebForm1.aspx):

<asp:DataGrid id="grdCustomer" style="Z-INDEX: 102; LEFT: 30px; POSITION: absolute; TOP: 152px" runat="server" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="3" Font-Size="X-Small" AutoGenerateColumns="False">

<SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#669999">

</SelectedItemStyle>

<AlternatingItemStyle BackColor="#FFF2F2"></AlternatingItemStyle>

<ItemStyle ForeColor="#000066" BackColor="#FAFFF9"></ItemStyle>

<HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#006699"></HeaderStyle>

<FooterStyle ForeColor="#000066" BackColor="White"></FooterStyle>

<Columns>

<asp:TemplateColumn HeaderText="序号">

<ItemTemplate>

<asp:label id="lable1" runat=server><%#GetCount()%></asp:label>

</ItemTemplate>

</asp:TemplateColumn>

<asp:BoundColumn DataField="CustomerID" HeaderText="客户ID"></asp:BoundColumn>

<asp:BoundColumn DataField="CompanyName" HeaderText="公司名称"></asp:BoundColumn>

<asp:BoundColumn DataField="City" HeaderText="城市"></asp:BoundColumn>

<asp:BoundColumn DataField="Address" HeaderText="地址"></asp:BoundColumn>

</Columns>

</asp:DataGrid>

  

后台(WebForm1.aspx.cs):

int count;

private void Page_Load(object sender, System.EventArgs e)

{

     if(!IsPostBack)

     {

SqlConnection cnn = new SqlConnection();

cnn.ConnectionString = "data source=localhost;initial catalog=Northwind;password=;"

         +"persist security info=True;user id=sa;workstation id=APJ062;packet size=4096";

          string sqlstr = "select Top 10 CustomerID, CompanyName, City, Address from Customers";

         cnn.Open();

         SqlDataAdapter ad = new SqlDataAdapter(sqlstr,cnn);

         DataTable dt = new DataTable();

         ad.Fill(dt);

grdCustomer.DataSource = dt;

         grdCustomer.DataBind();

     }

//自动记数函数,在前台调用

public int GetCount()

{

     return ++count ;

}