在这里主要实现DataGrid的一些显示表中的数据提供分页显示与DataGride实现排序功能
第一步取得DataTable PersonFunction是一个操作类,如果要获得连接对象调用createConnection方法
public static DataTable selectAllPerson()
{
DataSet ds = null;
try
{
SqlConnection conn = PersonFunction.createConnection();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand("select * from personInfo", conn);
ds = new DataSet();
sda.Fill(ds, "personInfo");
}
catch (Exception ex) {
ex.Message.ToString();
}
return ds.Tables["personInfo"];
}
第二部:将数据填充DataGrid控件
private void fillDataGrid()
{
try
{
DataGrid1.DataSource = PersonFunction.selectAllPerson();
DataGrid1.DataBind();
}
catch (Exception ex) {
ex.Message.ToString();
}
}
第三部:调用 在Page_load中调用
protected void Page_Load(object sender, EventArgs e)
{
this.fillDataGrid();
}
实现分页功能
在DataGrid控件中右上方有一个三角型按扭点击找到"属性生成器"在属性生成器中设置下面属性,在"分页"项中有复选框"允许分页"
需要选中就可以了
设置事件
DataGrid中双击PageIndexChanged事件
protected void dgShowPersonInfo_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
this.DataGrid1.CurrentPageIndex = e.NewPageIndex;
this.DataGrid1.DataBind();
}
设置排序
DataGrid设置
在DataGrid控件中右上方有一个三角型按扭点击找到"属性生成器"在属性生成器中设置下面属性,
在"常规"项中有复选框"允许排序"需要选中就可以了
事件设计
选中SortCommand事件
在事件中实现的代码
protected void dgShowPersonInfo_SortCommand(object source, DataGridSortCommandEventArgs e)
{
SqlConnection conn = PersonFunction.createConnection();
DataSet ds = new DataSet();
DataView dv = new DataView();
try
{
conn.Open();
string selectString = " select * from personInfo ";
SqlDataAdapter da = new SqlDataAdapter(selectString,conn);
da.Fill(ds,"person");
dv = ds.Tables["person"].DefaultView;
dv.Sort = e.SortExpression;
this.dgShowPersonInfo.DataSource = dv;
this.dgShowPersonInfo.DataBind();
}
catch
{
Response.Write("Error");
Response.End();
}
finally {
conn.Close();
}
}