Note that there are some explanatory texts on larger screens.

plurals
  1. POArgumentOutOfRangeException when sorting a DataGridView using a custom IComparer
    text
    copied!<h2>Setup</h2> <p>I have a piece of code that is sorting a DataGridView using a custom IComparer:</p> <pre><code>public class CustomComparer: IComparer { public int Compare(object x, object y) { DataGridViewRow row1 = (DataGridViewRow)x; DataGridViewRow row2 = (DataGridViewRow)y; if (row1.ReadOnly &amp;&amp; row2.ReadOnly) { return 0; } else if (row1.ReadOnly &amp;&amp; !row2.ReadOnly) { return 1; } else { return -1; } } </code></pre> <h2>Problem</h2> <p>Strangely, when I execute the following line (after populating the rows):</p> <pre><code>grid.Sort(new CustomComparer()); </code></pre> <p>I get an ArgumentOutOfRangeException with the message "Index was out of range. Parameter: index".</p> <h2>More Facts</h2> <p>Further investigation revealed the following:</p> <ul> <li>The DataGridView I'm sorting <em>doesn't</em> have a BindingSource on it - rows have been manually added.</li> <li>The Stack Trace of the error is only one level deep - it occurs on an InternalDictionary in mscorlib</li> <li>Strange fact #1 - This only happens if at any point, my custom comparer returns -1 for any of its comparisons</li> <li>If I change the Sort method to no longer use my CustomComparer, the exception is not thrown.</li> </ul> <h2>Workaround</h2> <p>This last fact led me to rewrite the Compare() method to defer to .NET's CompareTo method:</p> <pre><code>DataGridViewRow row1 = (DataGridViewRow)x; DataGridViewRow row2 = (DataGridViewRow)y; return row1.ReadOnly.CompareTo(row2.ReadOnly); </code></pre> <p>Which mysteriously <strong>worked</strong>. The exception is no longer thrown.</p> <p>So although I have a workaround, I wonder if anyone has any idea why this could possibly be a fix, and what the issue might have been in the first place. I've looked at the implementation of CompareTo and it <em>also</em> returns -1...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload