GridView without DataSourceControl DataSource

written by Ryan Olshan on Sunday, January 22 2006

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;

    }

Kick this post on .NET Kicks

Similar Posts

  1. C# GridView Sorting/Paging w/o a DataSourceControl DataSource
  2. VB.NET GridView Sorting/Paging w/o a DataSourceControl DataSource
  3. GridView Sorting

Comments

  • Giuliano Valentino on on 1.26.2006 at 8:37 AM

    Giuliano Valentino avatar

    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!

  • Ryan Olshan on on 1.26.2006 at 9:02 AM

    Ryan Olshan avatar

    From your comment, it sounds like the GridView isn't binding to the DataSource correctly or not binding at all. Is your code an identical match to what I have above? Could you post your code, or if it's too large e-mail it to Ryan(dot)Olshan(at)strongtypes(dot)com?

  • Giuliano Valentino on on 1.26.2006 at 9:13 AM

    Giuliano Valentino avatar

    I'm emailing you the code in a couple of seconds.

  • Ryan Olshan on on 1.26.2006 at 9:32 AM

    Ryan Olshan avatar

    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.

  • Patrick Fomin on on 1.31.2006 at 11:49 AM

    Patrick Fomin avatar

    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:



    <asp:GridView ID="usergrid" runat="server" AutoGenerateColumns="False" DataKeyNames="UserName" AllowSorting="True" AllowPaging="True" CellPadding="4" ForeColor="#333333" GridLines="None" PageSize="10" OnPageIndexChanging="usergrid_PageIndexChanging" OnSorting="usergrid_Sorting" OnSorted="usergrid_Sorted">




    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.");


    }

  • Ryan Olshan on on 2.02.2006 at 4:00 AM

    Ryan Olshan avatar

    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?

  • huzefa on on 2.07.2006 at 8:06 PM

    huzefa avatar

    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 htinwala@gmail.com




    '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

  • Ryan Olshan on on 2.08.2006 at 9:46 PM

    Ryan Olshan avatar

    huzefa,



    What does your GridView code look like?



    Ryan

  • huzefa on on 2.13.2006 at 10:16 PM

    huzefa avatar

    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 :



    <asp:GridView ID="gvSvA" runat="server" OnPageIndexChanging="gvSvAPageIndexChanging"


    OnSorting="gvSvASorting">


    <Columns>


    <asp:CommandField ShowSelectButton="True" />


    </Columns>


    </asp:GridView>



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



    <asp:GridView runat="server" AllowPaging="True" AllowSorting="True" CellPadding="4" GridLines="None" HorizontalAlign="Center" Font-Size="X-Small" Font-Names="Arial" ForeColor="Navy">


    <PagerSettings Mode="NumericFirstLast" />


    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />


    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />


    <RowStyle BackColor="#EFF3FB" />


    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />


    <EditRowStyle Font-Names="Arial" Font-Size="X-Small" BackColor="#2461BF"/>


    <AlternatingRowStyle BackColor="White" />


    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /></asp:GridView>



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



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



    Huzefa.

  • Ryan Olshan on on 2.14.2006 at 9:54 AM

    Ryan Olshan avatar

    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]);


    ...


    }


    }


  • gradiation on on 3.02.2006 at 3:09 PM

    gradiation avatar

    Any chance someone has an example for editing rows?

  • vidyashan on on 3.08.2006 at 10:40 AM

    vidyashan avatar

    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  

  • rolshan on on 3.08.2006 at 10:55 AM

    rolshan avatar

    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

  • BenJones on on 3.28.2006 at 10:45 AM

    BenJones avatar

    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 = SortTab

  • nirmal on on 4.09.2006 at 7:16 AM

    nirmal avatar

    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 problem

    can you help .i am very new to programming.

  • Uday Hebbar on on 4.18.2006 at 12:33 PM

    Uday Hebbar avatar

    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

  • Ryan Olshan on on 4.18.2006 at 1:16 PM

  • Uday Hebbar on on 4.18.2006 at 2:02 PM

    Uday Hebbar avatar

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







  • Ian Pollard on on 4.19.2006 at 5:44 AM

    Ian Pollard avatar

    Ryan,

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

    SortExpression = 'Ascending'
    SortExpression = 'ASC'

    ????

  • Ryan Olshan on on 4.19.2006 at 1:11 PM

    Ryan Olshan avatar

    Hi Uday,

    You need to bind to the data source on postback.

    HTH, Ryan

  • Ryan Olshan on on 4.19.2006 at 1:12 PM

    Ryan Olshan avatar

    Hi Ian,

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

    Thanks. Ryan

  • Norma on on 4.19.2006 at 9:27 PM

    Norma avatar

    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.

  • anowak on on 4.19.2006 at 9:35 PM

    anowak avatar

    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

  • Derek Young on on 5.03.2006 at 9:46 AM

    Derek Young avatar

    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

  • Ryan Olshan on on 5.03.2006 at 9:53 AM

    Ryan Olshan avatar

    Hi,

    Try removing the if (!IsPostBack).

    HTH,
    Ryan

  • Derek Young on on 5.03.2006 at 10:11 AM

    Derek Young avatar

    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

  • Ryan Olshan on on 5.03.2006 at 5:19 PM

    Ryan Olshan avatar

    DY,

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

    Ryan

  • DK on on 5.28.2008 at 8:16 AM

    DK avatar

    Thanks a Lot ...

  • babu kumarasamy on on 6.28.2008 at 12:42 AM

    babu kumarasamy avatar

    Hi,

    I am using only page not sorting. I don't to use viewstate.

    In this statement I got

    Object reference not set to an instance of an object.

    System.Type type = grdBasicSearchMaster.DataSource.GetType();

    protected void grdBasicSearchMaster_PageIndexChanging(object sender, GridViewPageEventArgs e)

    {

    System.Type type = grdBasicSearchMaster.DataSource.GetType();

    DataTable m_DataTable = grdBasicSearchMaster.DataSource as DataTable;

    grdBasicSearchMaster.DataSource = m_DataTable;

    grdBasicSearchMaster.DataBind();

    grdBasicSearchMaster.PageIndex = e.NewPageIndex;

    }

    Thanks in advance.

  • dhireshjawale on on 8.08.2008 at 7:44 AM

    dhireshjawale avatar

    Thanks a lot

    this is very good article that i had run without error.

  • LifeShines on on 12.18.2008 at 3:21 AM

    LifeShines avatar

    Thanks alot for this wonderful post! This is really very helpful.

    Great work!

Post a comment