方法一:
.aspx文件
<asp:DataGrid id="DataGrid1" style="Z-INDEX: 102; LEFT: 352px; POSITION: absolute; TOP: 96px"
runat="server" AutoGenerateColumns="False" PageSize="3" AllowPaging="True">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<!-- 这里是关键-->
<SPAN>
<!--<%# Container.ItemIndex+1 %>-->
<asp:Label id=lblRowNumber runat="server" Text='<%#
DataBinder.Eval(Container, "ItemIndex", "{0}") %>'/>
</SPAN>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="CategoryName"></asp:BoundColumn>
<asp:BoundColumn DataField="Description"></asp:BoundColumn>
</Columns>
</asp:DataGrid>
.aspx.cs后台
public DataSet ds;//定义全局DataSet
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if (Page.IsPostBack==false)
{
Data_Bind();
}
}
private void Data_Bind(){
ds=new DataSet();
string strConnection ="server=localhost;database=Northwind;uid=sa;pwd=sa";
SqlConnection myConnection = new SqlConnection(strConnection);
SqlDataAdapter myAdapter = new SqlDataAdapter("SELECT CategoryName, Description FROM
Categories",myConnection);
// 为了分页方便ds是一个全局的变量
myAdapter.Fill(ds);
this.DataGrid1.DataSource = ds.Tables[0].DefaultView;
this.DataGrid1.DataBind();
}
private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs
e)
{//分页
DataGrid1.CurrentPageIndex=e.NewPageIndex;
Data_Bind();
}
方法二(支持分页)
.aspx文件
<asp:DataGrid id="DataGrid1" style="Z-INDEX: 102; LEFT: 248px; POSITION: absolute; TOP: 112px"
runat="server" AllowPaging="True" PageSize="3" AutoGenerateColumns="False">
<Columns>
<asp:BoundColumn DataField="RowNumber"
HeaderText="RowNumber"></asp:BoundColumn>
<asp:BoundColumn DataField="CategoryName"></asp:BoundColumn>
<asp:BoundColumn DataField="Description"></asp:BoundColumn>
</Columns>
</asp:DataGrid>
.aspx.cs后台
public DataSet ds;//定义全局DataSet
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(Page.IsPostBack==false)
{
Data_Bind();
}
}
private void Data_Bind(){
ds=new DataSet();
string strConnection ="server=localhost;database=Northwind;uid=sa;pwd=sa";
SqlConnection myConnection = new SqlConnection(strConnection);
SqlDataAdapter myAdapter = new SqlDataAdapter("SELECT CategoryName, Description FROM
Categories",myConnection);
// 为了分页方便ds是一个全局的变量
myAdapter.Fill(ds);
//调用GetRowNumberTable
this.DataGrid1.DataSource = this.GetRowNumberTable(ds.Tables[0]).DefaultView;
this.DataGrid1.DataBind();
}
private DataTable GetRowNumberTable(DataTable dt)
{
DataColumn col = new DataColumn("RowNumber",Type.GetType("System.Int32"));
dt.Columns.Add(col);
for(int i = 0;i<=dt.Rows.Count-1;i++)
{
if(0 == i)
dt.Rows[i][col] = 1;
else
dt.Rows[i][col] = Convert.ToInt32(dt.Rows[i-1][col]) +1;
}
return dt;
}
private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs
e)
{//分页
DataGrid1.CurrentPageIndex=e.NewPageIndex;
Data_Bind();
}