How to remove gaps in DListView Indexing

If you remove a line in a DListView its number position is not taken by the value above it.

eg. if the index is on the left and the value on the right this is what will happen when a line is removed:



1   fish
2   dog
3   bird
4   cat
5   bear


Line 2 removed



1   fish
3   bird
4   cat
5   bear


How do I get it so it would indexed like so after a line is removed?



1   fish
2   bird
3   cat
4   bear


I haven’t worked too much with DListView, but from what I see, you could just resort it, and it should pop everything back into correct locations.

Or, keep a table containing all of the data that is used with the DListView and remove from that, then reload the DListView.

Is there a convenient one line command for resorting?

You could always do DListView:Clear() and then reinsert the lines, which is probably the easiest way.

Alternatively, you could do a loop for all of the lines that are after the index that you just removed and just decrease the index value by one.

For example, something like this (untested):



function PANEL:RemoveAndResort( x )
    self:RemoveLine( x )

    local line

    for i = x, #self:GetLines() do
        line = self:GetLine( i )
        line:SetValue( 1, line:GetValue( 1 ) - 1 ) -- assuming index 1 is the visible numeric index
    end
end


If you remove the line at index 2, then the line at index 3 becomes the new index 2. So, using the same index of the line you just removed, this loops through all of the remaining lines from that index and decreases their visible index value by 1 manually.