Showing posts with label Paging. Show all posts
Showing posts with label Paging. Show all posts

Wednesday, June 25, 2008

GridView ObjectDataSource Paging

Took me a lot of time to figure it out...

First, paging doesn't seem to work when ObjectDataSource Select function returns SqlDataReader so it returns DataView now.

The code looks like this:

   1: [DataObjectMethod(DataObjectMethodType.Select)]
   2:     public static DataView GetRows(int statusid, int experienceid, string submitter, string idsid, string SortExpression)
   3:     {
   4:  
   5:         StringBuilder strSql = MainSelectSql(idsid, statusid, experienceid, submitter, SortExpression);
   6:  
   7:         SqlConnection connection = Connection.GetConnection();
   8:         SqlCommand command = new SqlCommand(strSql.ToString(), connection);
   9:         command.CommandType = CommandType.Text;
  10:         SqlDataAdapter adapter = new SqlDataAdapter(command);
  11:  
  12:         //connection.Open();
  13:         DataTable dt = new DataTable();
  14:         adapter.Fill(dt);
  15:         connection.Close();
  16:         int totalRecords = dt.Rows.Count;
  17:  
  18:         DataView dw = new DataView(dt);
  19:  
  20:         return dw;
  21:     }

 

The GridView has to have its "AllowPaging" set to true and PageIndexChanging method looks like this:

   1: protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
   2: {
   3:     GridView gv = (GridView)sender;
   4:     gv.PageIndex = e.NewPageIndex;
   5:     gv.DataBind();
   6: }

 

Also can change the page size in properties...

Saturday, March 22, 2008

Paging and Sorting in GridView without using Datasource control

 

<asp:GridView ID="gridView" OnPageIndexChanging="gridView_PageIndexChanging" 
OnSorting="gridView_Sorting" runat="server" />
private string ConvertSortDirectionToSql(SortDirection sortDireciton)
{
   string newSortDirection = String.Empty;
   switch (sortDirection)
   {
      case SortDirection.Ascending:
         newSortDirection = "ASC";
         break;
      case SortDirection.Descending:
         newSortDirection = "DESC";
         break;
   }
   return newSortDirection
}
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
   gridView.PageIndex = e.NewPageIndex;
   gridView.DataBind();
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
   DataTable dataTable = gridView.DataSource as DataTable;
   if (dataTable != null)
   {
      DataView dataView = new DataView(dataTable);
      dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
      gridView.DataSource = dataView;
      gridView.DataBind();
   }
}

Source