如何让DataGrid自动生成序号

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

代码实现:

前台( WebForm1.aspx ):

 1<asp:datagrid autogeneratecolumns="False" backcolor="White" bordercolor="#CCCCCC" borderstyle="None" borderwidth="1px" cellpadding="3" font-size="X-Small" id="grdCustomer" runat="server" style="Z-INDEX: 102; LEFT: 30px; POSITION: absolute; TOP: 152px">
 2<selecteditemstyle backcolor="#669999" font-bold="True" forecolor="White">
 3</selecteditemstyle>
 4<alternatingitemstyle backcolor="#FFF2F2"></alternatingitemstyle>
 5<itemstyle backcolor="#FAFFF9" forecolor="#000066"></itemstyle>
 6<headerstyle backcolor="#006699" font-bold="True" forecolor="White"></headerstyle>
 7<footerstyle backcolor="White" forecolor="#000066"></footerstyle>
 8<columns>
 9<asp:templatecolumn headertext="  序号  ">
10<itemtemplate>
11<asp:label id="lable1" runat="server">```
12#GetCount()
13```</asp:label>
14</itemtemplate>
15</asp:templatecolumn>
16<asp:boundcolumn datafield="CustomerID" headertext="  客户  ID"></asp:boundcolumn>
17<asp:boundcolumn datafield="CompanyName" headertext="  公司名称  "></asp:boundcolumn>
18<asp:boundcolumn datafield="City" headertext="  城市  "></asp:boundcolumn>
19<asp:boundcolumn datafield="Address" headertext="  地址  "></asp:boundcolumn>
20</columns>
21</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 ;

}

Published At
Categories with Web编程
Tagged with
comments powered by Disqus