aspx代码如下
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Debug="true" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<asp:DataGrid ID="dg" runat="server" AutoGenerateColumns="true" OnSortCommand="gridsort" AllowPaging="true" AllowSorting="true"
PageSize="3" PagerStyle-NextPageText="下一页" PagerStyle-PrevPageText="上一页" OnPageIndexChanged="changepage"
CellPadding="2" CellSpacing="2" BorderColor="black" BorderWidth="1" Font-Names="vandana" BorderStyle="solid" Font-Size="x-small" >
<AlternatingItemStyle BackColor="paleGoldenrod" />
<ItemStyle BackColor="beige" />
</asp:DataGrid>
<asp:Label ID="pagenumber" runat="server" />
<asp:Label ID="totalnumber" runat="server" />
</form>
</body>
</html>
.cs代码如下
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected string strConnString = "Data Source=127.0.0.1;uid=sa;pwd=;Initial Catalog=chapter;";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) bindgrid();
}
public void gridsort(object serder, DataGridSortCommandEventArgs e)
{
Session["sortexpression"] = e.SortExpression;
bindgrid();
}
public void changepage(object serder,DataGridPageChangedEventArgs e)
{
dg.CurrentPageIndex = e.NewPageIndex;
pagenumber.Text = "第" + dg.CurrentPageIndex + "页";
bindgrid();
}
public void bindgrid()
{
int total;
SqlConnection sqlconn = new SqlConnection(strConnString);
SqlDataAdapter sqld=new SqlDataAdapter ("select * from student", strConnString);
DataSet ds = new DataSet();
sqlconn.Open();
sqld.Fill(ds, "tabstud");
total = ds.Tables["tabstud"].Rows.Count;
totalnumber.Text="共"+((total-total%dg.PageSize)/dg.PageSize+1).ToString()+"页";
if (total == 0)
{
pagenumber.Text = "没有可以显示的记录";
return;
}
if (Session["sortexpression"] != "")
{
DataTable dtable = ds.Tables["tabstud"];
DataView dview = new DataView(dtable);
dview.Sort = Session["sortexpression"].ToString();
dg.DataSource = dview;
}
else dg.DataSource = ds.Tables["tabstud"];
dg.DataBind();
sqlconn.Close();
sqlconn = null;
}
}
提示错误如下
异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。
源错误:
行 49: DataTable dtable = ds.Tables["tabstud"];
行 50: DataView dview = new DataView(dtable);
行 51: dview.Sort = Session["sortexpression"].ToString();
行 52: dg.DataSource = dview;
行 53: }
帅哥美女们帮我看看错在哪了
[此贴子已经被作者于2007-6-1 23:34:47编辑过]