Changeing the order of records in a bound datagrid using Up/Down buttons

Posted on 2005-05-17
Last Modified: 2010-04-23
My users would like to reorder the records in a bound datagrid by using Up/Down buttons.  The DG also manages additions/deletetions of records.  I have tried adding a field in the table to hold the SortOrderValue.  When moving a record up or down I can increase/decrease the SortOrderValue by 1 and rewrite the record to the database, but how do I change the SortOrderValue of the "other" record that is being reordered?   I guess what I'm asking is after updating the SortOrderValue for the selected record, how do I determine which other record will be affected so I can correct its SortOrderValue.

Thanks in advance,

Question by:TMHPROG
    LVL 8

    Expert Comment

    Use a CurrencyManger to loop through all records next to the record you change and set previous order value + 1
    LVL 3

    Accepted Solution

    To move a record, you have to swap its ordinal with the one of the element in the position you want to move it to.
    So to move record N one position upwards, you have to swap elements N and N-1, which is done by:

    UPDATE table SET SortOrderValue = -1 WHERE SortOrderValue = N
    UPDATE table SET SortOrderValue = N WHERE SortOrderValue = N - 1
    UPDATE table SET SortOrderValue = N - 1 WHERE SortOrderValue = -1

    To move it down, replace 'N - 1' with 'N + 1'.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
    It’s quite interesting for me as I worked with Excel using for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
    Internet Business Fax to Email Made Easy - With eFax Corporate (, you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
    Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

    734 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now