Welcome to Strong Coders Community Sign in | Join | Help

Blog ( Of Ryan Olshan)

News

  • About Ryan Olshan

    Join StrongTypes - Free Generics Help By Email
    Join StrongTypes

    Community Credit Winner

    View my MVP profile

    The posts on this weblog are provided "as is" with no warranties and confer no rights. The opinions expressed herin are my own personal opinions and do not represent my employer's view in any way.

    Subscribe to Rolog via My AOL
    Subscribe to Rolog via Bloglines


    Subscribe to Rolog via Feedburner

    Furl Rolog




    Subscribe to Rolog via Newsburst


    Subscribe to Rolog via Pluck

    Add Rolog to Technorati Favorites




    Thycotic Secret Server

.NET Websites

  • => StrongTypes.com <=
  • Community Credit
  • DotNetCharity.com
  • DotNetSlackers
  • EasyListBox
  • SystemNetMail.com
  • SystemWebMail.com

Blogroll

  • Alex Campbell
  • Carlos Magalhaes
  • Chris Taylor
  • Darren Neimke
  • David Betz
  • Eric Smith
  • Rob Caron
  • Rob Howard
  • Sam Gentile
  • Scott Guthrie
  • Scott Mitchell
  • Tess
  • Wesner Moise
  • Jason Alexander
  • Bill Ryan
  • Steve Smith
  • Sahil Malik
  • David Silverlight

Other Websites

  • 911 Pigeon Alert
  • Pacific Wildlife Project

Strong Coder Bloggers

  • Dean Fiala
  • Kevin Jones

Thycotic Bloggers

  • Bryant Smith
  • John Morales
  • Jonathan Cogley

Yahoo! Groups

  • => StrongTypes <=
  • AspNet2
  • AspNet20GridView
  • PayPalDevDotNet
  • RubyOnRails
  • VSTS

GridView without DataSourceControl DataSource

If you're like me and converting a .NET 1.1 application to 2.0, and aren't using a DataSourceControl DataSource just yet but need to enable sorting and paging, you might run into the following exceptions:

When changing the page:

The GridView 'GridViewID' fired event PageIndexChanging which wasn't handled.

When clicking a column name to sort the column:

The GridView 'GridViewID' fired event Sorting which wasn't handled.

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

   

     < asp : GridView ID ="gridView" AllowPaging ="true" AllowSorting ="true "

         OnPageIndexChanging ="gridView_PageIndexChanging" OnSorting ="gridView_Sorting"

         runat ="server" />

 

    private string GridViewSortDirection

    {

        get { return ViewState[ "SortDirection" ] as string ?? "ASC" ; }

        set { ViewState[ "SortDirection" ] = value ; }

    }

 

    private string GridViewSortExpression

    {

        get { return ViewState[ "SortExpression" ] as string ?? string .Empty; }

        set { ViewState[ "SortExpression" ] = value ; }

    }

 

    private string GetSortDirection()

    {

        switch (GridViewSortDirection)

        {

            case "ASC" :

                GridViewSortDirection = "DESC" ;

                break ;

 

            case "DESC" :

                GridViewSortDirection = "ASC" ;

                break ;

        }

 

        return GridViewSortDirection;

    }

 

    protected void gridView_PageIndexChanging( object sender, GridViewPageEventArgs e)

    {

        gridView.DataSource = SortDataTable(gridView.DataSource as DataTable , true );

        gridView.PageIndex = e.NewPageIndex;

        gridView.DataBind();

    }

 

    protected DataView SortDataTable( DataTable dataTable, bool isPageIndexChanging)

    {

        if (dataTable != null )

        {

            DataView dataView = new DataView (dataTable);

            if (GridViewSortExpression != string .Empty)

            {

                if (isPageIndexChanging)

                {

                    dataView.Sort = string .Format( "{0} {1}" , GridViewSortExpression, GridViewSortDirection);

                }

                else

                {

                    dataView.Sort = string .Format( "{0} {1}" , GridViewSortExpression, GetSortDirection());

                }

            }

            return dataView;

        }

        else

        {

            return new DataView ();

        }

    }

 

    protected void gridView_Sorting( object sender, GridViewSortEventArgs e)

    {

        GridViewSortExpression = e.SortExpression;

        int pageIndex = gridView.PageIndex;

        gridView.DataSource = SortDataTable(gridView.DataSource as DataTable , false );

        gridView.DataBind();

        gridView.PageIndex = pageIndex;

    }

Share this post: | bookmark it! | digg it! | reddit! | kick it! | live it!
Posted: Sunday, January 22, 2006 1:26 PMby Ryan Olshan
Filed under: ,

Comments

Giuliano Valentino said:

Thanks for the code above. It's actually a relief not to get the error anymore!

The problem now is that when I click on my header name (after setting up a sort expression) it does not change the sort order. The event fires but the page looks the same as it did before.

As well, when I select a new page from the index on the bottom it displays the error message I set up to return where there are no records that march a query.

I'm sure there is something simple I'm missing here. Is there anything else I should provide?

Thanks!
# January 26, 2006 8:37 AM

Ryan Olshan said:

# January 26, 2006 9:02 AM

Giuliano Valentino said:

I'm emailing you the code in a couple of seconds.
# January 26, 2006 9:13 AM

Ryan Olshan said:

Just replied. The line in the gridView_Sorting method in your code that concatinates the SortExpression should look like m_DataView.Sort = e.SortExpression & " " & ConvertSortDirectionToSql(e.SortDirection) since you are coding in VB.NET.
# January 26, 2006 9:32 AM

Patrick Fomin said:

I still dont get the sorting to work (paging works), i have the same problem as Giuliano. I copied your code and it just dosent work. Here is the the code that is dealing with it:




MembershipUserCollection mUsers;

protected void Page_Load(object sender, EventArgs e)
{
mUsers = Membership.GetAllUsers();
usergrid.DataSource = mUsers;

if (!this.IsPostBack)
{
usergrid.DataBind();
}
}

public void usergrid_PageIndexChanging (object sender, GridViewPageEventArgs e)
{
usergrid.PageIndex = e.NewPageIndex;
usergrid.DataBind();
}
public void usergrid_Sorting (object sender, GridViewSortEventArgs e)
{
DataTable m_DataTable = usergrid.DataSource as DataTable;

if (m_DataTable != null)
{
DataView m_DataView = new DataView(m_DataTable);
m_DataView.Sort = e.SortExpression + " " + e.SortDirection;

usergrid.DataSource = m_DataView;
usergrid.DataBind();
}
}

public void usergrid_Sorted (object sender, EventArgs e)
{
Response.Write("Sorting by " +
usergrid.SortExpression.ToString() +
" in " + usergrid.SortDirection.ToString() +
" order.");
}
# January 31, 2006 11:49 AM

Ryan Olshan said:

Hi Patrick,

When you say you can't get sorting to work, what happens? Does it not work at all? Is an exception raised? Also, do you have a value for the SortExpression property of the column you want to sort assigned a value?
# February 2, 2006 4:00 AM

huzefa said:

Hi Rolshan....

Wel I have been trying to get the sorting event to work but in vain. even made the change as u mentioned above about the '&', since i too am coding in VB.Net. the paging works great (although after re-entering data into the dataset of the gridview ...) but just cant get the sort feature to work ..... if u cld look at the code and see wat was wrong, then i wld be obliged ..... thanks a lot in advance !!!

ps: pls .... i need this very urgently ..... reply here or mail me at


'code starts here

Protected Sub gvSvAPageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)

gvSvA.PageIndex = e.NewPageIndex
gvSvA.DataSource = ws.gvSvAselect(ddlLoc.SelectedValue, ddlMvmtLoc.SelectedValue, ddlNextAction.SelectedValue, _
ddlMvmtStatus.SelectedValue, ddlBatchNo.SelectedValue, ddlSeg.SelectedValue, _
ddlPL.SelectedValue)
gvSvA.DataBind()

End Sub


Private Function ConvertSortDirectionToSql(ByVal sortdirection As SortDirection) As String

Dim msortdirection As String = String.Empty
Select Case sortdirection

Case sortdirection.Ascending
msortdirection = "ASC"
Return msortdirection
Exit Function

Case sortdirection.Descending
msortdirection = "DESC"
Return msortdirection
Exit Function
End Select
Return msortdirection

End Function


Protected Sub gvSvASorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)

Dim mdatatable As DataTable = CType(gvSvA.DataSource, DataTable)

If Not (mdatatable Is Nothing) Then
Dim mdataview As DataView = New DataView(mdatatable)
mdataview.Sort = e.SortExpression & " " & ConvertSortDirectiontoSql(e.SortDirection)
gvSvA.DataSource = mdataview
gvSvA.DataBind()
End If

End Sub
# February 7, 2006 8:06 PM

Ryan Olshan said:

huzefa,

What does your GridView code look like?

Ryan
# February 8, 2006 9:46 PM

huzefa said:

Hi Rolshan....

real sorry for not getting back immediately ....
anyways, as i said earlier, i am binding my gridview to a dataset which i pass from a webservice.... so the binding is done at the server side in VB.Net ... thru these 2 lines ...

gvSvA.DataSource = ws.gvSvAselect(ddlLoc.SelectedValue, ddlMvmtLoc.SelectedValue, ddlNextAction.SelectedValue, ddlMvmtStatus.SelectedValue, ddlBatchNo.SelectedValue, ddlSeg.SelectedValue, ddlPL.SelectedValue)
gvSvA.DataBind()

on the Aspx page all i write for the gridview is :

OnSorting="gvSvASorting">





But i am also using themes and have an entry in a skin for gridviews in general which is :











Hope you can figure something out of this ...........

Thanks a lot in advance ...........

Huzefa.
# February 13, 2006 10:16 PM

Ryan Olshan said:

Huzefa,

Since you are using a DataSet, you will need to modify the sorting code to something like I have below, as the one I have posted uses a DataTable.

protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataSet m_DataSet = gridView.DataSource as DataSet;

if (m_DataSet != null)
{
DataView m_DataView = new DataView(m_DataSet.Tables[0]);
...
}
}
# February 14, 2006 9:54 AM

said:

I've created a live working example of my blog entry GridView without DataSourceControl with source code.GridView...
# February 18, 2006 3:23 PM

said:

I've created a live working example of my blog entry GridView without DataSourceControl with source code.GridView...
# February 18, 2006 3:34 PM

said:

I've created a live working example of my blog entry GridView without DataSourceControl with source code.Live...
# February 23, 2006 9:13 PM

said:

I've created a live working example of my blog entry GridView without DataSourceControl with source code.Live...
# February 25, 2006 8:26 PM

gradiation said:

Any chance someone has an example for editing rows?
# March 2, 2006 3:09 PM

vidyashan said:

Bothing paging and sorting works - But if you look closely in sorting Descending order is never fired. First time when you click on the header portion if takes Ascending - and also the second time.

Anybody noticed this??

Sri  
# March 8, 2006 10:40 AM

Ryan Olshan said:

Hi Sri,

Soon after posting that I noticed that sorting didn't work in both directions. There is now sample code and a live working examples of this in both VB.NET and C#, where sorting working in both directions. See the following blog entries:

VB.NET - http://blogs.strongcoders.com/blogs/ryan/archive/2006/02/23/575.aspx

C# - http://blogs.strongcoders.com/blogs/ryan/archive/2006/02/18/555.aspx

Ryan
# March 8, 2006 10:55 AM

BenJones said:

I came across this trying to do an admin panel for membership and profiles.  I had users first and last name stored in the profiles.  Since the default sql profile provider doesn't have a method that I'm aware of, I load the username, and "lastname, firstname" field into a datatable and bind that to a gridview.  This needs to act like all the other gridviews with sorting and paging, which is where your code has been helpful.  But the sorting doesn't hold when pages are changed.  I made some mods and changed it.

Source: http://www.learnasp.com/freebook/learn/cs_GridViewSortingNoDataSourceControl.aspx

1) I put the PopulatePublishersGridView(); in the Page_Init event method.  I believe this calls the method once instead of everytime the page loads.  The gridview control stores the information on subsequent page loads in the viewstate.

2)I would think that after the GridView control's DataSource is set to a DataTable it would be saved in the ViewState.  So if you changed the DataTable in the GridView's DataSource, those changes would be reflected in the GridView and saved in the ViewState.

That means if you sort the table, thus changing the table, then rebind it, thus saving it to the GridView, then those changes would also be reflected in the ViewState so when you change pages of the GridView control, the info would still be sorted.

It doesn't seem to work that way.  Maybe I'm missing something more fundamental in how these things work.  But I worked around this by saving the sort field in the ViewState and sorting in the PageIndexChanged event method.

3) Just like the GridViewSortDirection, I saved a GridViewSortExpression.

    private String GridViewSortExpression
    {
        get { return ViewState["SortExp"] as String ?? ""; }
        set { ViewState["SortExp"] = value; }
    }

4)In the "gridViewPublishers_Sorting" event method, I added:

     GridViewSortExpression = e.SortExpression;

5)To keep from having redundant code in the Sorting and PageIndexChanging event methods, I created a function for the sorting:

     protected DataView SortTable (DataTable dt)
    {
        DataView dv=new DataView();
        if (dt != null)
        {
            dv = new DataView(dt);
            if(GridViewSortExpression != "")
            {
                dv.Sort = GridViewSortExpression + " " +  
                GridViewSortDirection;
             }
        }
        return dv;
    }

6) I then added:

    gridView.DataSource = SortTable(gridView.DataSource as
                                         DataTable);

to the PageIndexChanging and replaced code in the Sorting event methods.

7) I haven't fully tested, but it seems to work.

# March 28, 2006 10:45 AM

nirmal said:

hi i have been using strongly typed datatable as a datasource for the grid view. What i have to do is to sort the gridview on click of buttons located on different location on the page.This i have done by sorting the table itself by using the select method of the datatable and rebinding it to the gridview.so far so good!!.I also have added a checkbox in the templete column of the gridview.This checkbox changes the value from 0 to 1 or from 1 to 0 in the database.I have bounded this checkbox in the gridviews rowbound event.My problem is that when i try to go to next page (I have allowed paging) a error is thrown on this line of binding checkbox int intEventId = (int)MyEventHistoryGridView.DataKeys[e.Row.DataItemIndex].Value;it says dataitem index is out of bounds.prior to binding my checkbox to a datasource there was no problemcan you help .i am very new to programming.
# April 9, 2006 7:16 AM

Uday Hebbar said:

Hi Ryan:

Firstly.. Thanks for your excellent work..

I think I have this working if I remove this sentence (Using VB Version with data table)

If Not Page.IsPostBack

Can you help me get sorting working with this piece of code there..

Thanks

# April 18, 2006 12:33 PM

Ryan Olshan said:

# April 18, 2006 1:16 PM

Uday Hebbar said:

Ryan I checked out the examples and the VB Net example does not have the If Not Page.IsPostBack





# April 18, 2006 2:02 PM

Ian Pollard said:

Ryan,

When I tried this the eventargs param e in gridView_Sorting method contained the following values:

SortExpression = 'Ascending'
SortExpression = 'ASC'

????

# April 19, 2006 5:44 AM

Ryan Olshan said:

Hi Uday,

You need to bind to the data source on postback.

HTH, Ryan

# April 19, 2006 1:11 PM

Ryan Olshan said:

Hi Ian,

Could you provide a little more background information on your issue?

Thanks. Ryan

# April 19, 2006 1:12 PM

Norma said:

Hi Ryan,

I'm stuck at stage one! I cannot get the sorting event to fire!

I'm working in VB.Net. I've added the OnSorting event handler to the aspx file as you suggested above.

I don't assign a datasource to the GridView via the design interface, but do it in my code in the Page_Load Event:

        If Not Page.IsPostBack Then
            myDS = al.dlGet_All_Budgets("vch_Code")
            GridView1.DataSource() = myDS
            GridView1.DataBind()
        End If

This successfully displays the GridView with data.

In the .aspx.vb file I have the following statement in my GridView1_Sorting Event:
 Label2.Text = "SORTING!"

I've put a breakpoint on this line and the breakpoint is never reached and the Label2 display never changes when I run the code and click madly all over the grid!

I'd be so grateful if you can tell me where I'm going wrong. It's driving me nuts!

Thanks - Norma.

# April 19, 2006 9:27 PM

anowak said:

Hi Ryan,

This is a great article although I am having trouble with the custom paging. I have setup a stored procedure to do my paging  so that I only get the amount of data I need. I can currently do this using an ObjectDataSource. The ObjectDataSource has a method SelectCountMethod which tells the gridview how many items are expected.

Now how would I do this using code behind without the DataSourceObject. The old DataGrid control used to have a property VirtualItemCount although they seem to have got rid of this in the GridView.

Any Ideas

# April 19, 2006 9:35 PM

said:

# April 24, 2006 8:43 AM

Derek Young said:

Hi, Guys,

Could you please help me find what's issue for my code? It's never worked. Somehow it is DataAdapter and GridView.DataSource never related I think. Here is the code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            MixDesignTableAdapter dsM = new MixDesignTableAdapter();

            GridView1.DataSource = dsM.GetData();
            GridView1.DataBind();
        }
    }

    protected void GridView_Sort(object sender, GridViewSortEventArgs e)
    {
        DataSet mDataSet = GridView1.DataSource as DataSet;

        if (mDataSet != null)
        {
            DataView mDataView = new DataView(mDataSet.Tables[0]);
            mDataView.Sort = e.SortExpression + " " + ConvtSortDir2SQL();

            GridView1.DataSource = mDataView;
            GridView1.DataBind();
            errMsg.Text = e.SortExpression.ToString() + " | " + e.SortDirection.ToString();
        }
    }
 It seems app never goes into if block, i.e. mDataSet is NULL.

Help, please help me! Thanks a lot!!!


DY

# May 3, 2006 9:46 AM

Ryan Olshan said:

Hi,

Try removing the if (!IsPostBack).

HTH,
Ryan

# May 3, 2006 9:53 AM

Derek Young said:

Hi, Ryan,

Thanks for your quick response.
I tried to remove postback, but it still just fresh and not do sorting. I have a label show some text in if block, it seems still not goes into. Have any idea, suggestion?
Thanks,

DY

# May 3, 2006 10:11 AM

Ryan Olshan said:

DY,

How does your code compare to the example at http://blogs.strongcoders.com/blogs/ryan/archive/2006/02/18/555.aspx ?

Ryan

# May 3, 2006 5:19 PM

said:

I just updated my GridView without DataSourceControl DataSource blog entry and all code to allow sort
# August 8, 2006 9:32 PM

said:

I just updated my GridView without DataSourceControl DataSource blog entry and all code to allow sort
# August 28, 2006 6:51 PM

said:

I just updated my GridView without DataSourceControl DataSource blog entry and all code to allow sort
# October 1, 2006 10:07 PM
New Comments to this post are disabled