views:

10

answers:

1

I have an asp.net ListView that is sortable.

I have a button with a "select" command name. When I click on the button the appropriate row gets selected. If I then click on a sort header the ListView will sort, but the selected index will stay the same. In other words if I click the 2nd row then sort the 2nd row is still selected.

Is there a way to make the ListView select the appropriate row after it sorts so that if I click an item then sort the same item will still be selected but in a different position depending on the sort?

+1  A: 

You have to do it programmatically - although the solution is somewhat nasty. First step is to define DataKeys and onSorting and Sorted events in ListView as below

  <asp:ListView ID="ListView1" runat="server"  DataSourceID="SqlDataSource1"  DataKeyNames="AddressId,AddressLine1"
            onsorting="ListView1_Sorting" onsorted="ListView1_Sorted">

Then in the code behind you have to handle the events.Since the DataItems on the Items collection is always null and DataIndex and DisplayIndex are not set as one would normally expect we have to use DataKeys.Store datakey of selected Item before sort and after sort search through DatakEy collection to match with stored datakey. See below

 private DataKey dk;

        protected void ListView1_Sorting(object sender, ListViewSortEventArgs e)
        {
          dk=  (ListView1.SelectedIndex > 0) ? ListView1.DataKeys[ListView1.SelectedIndex] : null;
        }
        protected void ListView1_Sorted(object sender, EventArgs e)
        {
            if (dk == null) return;
            int i;
            ListView1.DataBind();
            for (i = 0; i < ListView1.DataKeys.Count; i++)
               if(AreEqual(ListView1.DataKeys[i].Values,dk.Values)) break;
            if (i >= ListView1.DataKeys.Count) return;
            ListView1.SelectedIndex =i;
        }
        private bool AreEqual(System.Collections.Specialized.IOrderedDictionary x, System.Collections.Specialized.IOrderedDictionary y)
        {
            for (int i = 0; i < x.Count; i++)
                if (!x[i].Equals(y[i])) return false;
            return true;
        }
josephj1989
Thanks, I started going down this path, but was hoping there would be something easier build into the control.
metanaito