How to fix Error on Paging in datagrid

Friday, April 17, 2009

If you set AllowPaging="true" or AllowSorting="true" on a GridViewcontrol without using a DataSourceControl DataSource (i.e.SqlDataSource, ObjectDataSource), you will run into the followingerrors:



When changing the page on the GridView control:



TheGridView 'GridViewID' fired event PageIndexChanging which wasn'thandled.



When clicking a column name to sort the column on theGridView control:



The GridView 'GridViewID' fired event Sorting whichwasn't handled.



As a result of not setting the DataSourceID propertyof the GridView to a DataSourceControl DataSource, you have to add eventhandlers for sorting and paging.



OnPageIndexChanging="gridView_PageIndexChanging"OnSorting="gridView_Sorting" runat="server" />



private stringConvertSortDirectionToSql(SortDirection sortDireciton)

{

stringnewSortDirection = String.Empty;



switch (sortDirection)

{

case SortDirection.Ascending:

newSortDirection = "ASC";

break;



case SortDirection.Descending:

newSortDirection = "DESC";

break;

}



returnnewSortDirection

}



protected void gridView_PageIndexChanging(objectsender, GridViewPageEventArgs e)

{

gridView.PageIndex =e.NewPageIndex;

gridView.DataBind();

}



protected voidgridView_Sorting(object sender, GridViewSortEventArgs e)

{

DataTable dataTable = gridView.DataSource as DataTable;



if(dataTable != null)

{

DataView dataView = newDataView(dataTable);

dataView.Sort = e.SortExpression + " " +ConvertSortDirectionToSql(e.SortDirection);



gridView.DataSource= dataView;

gridView.DataBind();

}

}

0 comments

Post a Comment

LinkWithin

Blog Widget by LinkWithin

Recommended Books