0

How to access DataGridView.SelectedRows in reverse order using foreach?

Which one is better foreach or for loop in C#?
Below code snippet giving rows in reverse order if I select mulitple rows.

public static DataTable GetSelectedData(DataGridView dgv)
    {
        DataTable selectedData = new DataTable();

        foreach (DataGridViewColumn col in dgv.Columns)
        {
            selectedData.Columns.Add(col.Name, col.ValueType != null ? col.ValueType : typeof(string));
        }

        foreach (DataGridViewRow selectedRow in dgv.SelectedRows)
        {
            var dtRow = selectedData.NewRow();
            for (int i1 = 0; i1 < dgv.Columns.Count; i1++)
                dtRow[i1] = (selectedRow.Cells[i1].Value == null ? DBNull.Value : selectedRow.Cells[i1].Value);
            selectedData.Rows.Add(dtRow);
        }

        return selectedData;
    }

I need an efficient way to retrieve rows in order actually in the datagridview.

1 Answers1

0

You have two options

(A) Use reverse for loop instead of foreach

for (int i = dgv.SelectedRows.Count - 1; i >= 0; i--)
{
    var selectedRow = dgv.SelectedRows[i];
    // ...
}

(B) Create an extension method like this

public static class DataGridViewExtensions
{
    public static IEnumerable<DataGridViewRow> GetSelectedRows(this DataGridView source)
    {
        for (int i = source.SelectedRows.Count - 1; i >= 0; i--)
            yield return source.SelectedRows[i];
    }
}

and use it as follows

foreach (var selectedRow in dgv.GetSelectedRows())
{
    // ...
}
Ivan Stoev
  • 159,890
  • 9
  • 211
  • 258
  • Actually, I am looking for solution using foreach.. If I use for loop here, does it impact performance of code? – Vikrant Mishra Dec 22 '15 at 11:08
  • @VikrantMishra Actually the `for` loop is faster than `foreach`. Option (B) is provided for your convinience - to use the "familiar" `foreach` when needed. And btw, what do you mean by `I'm looking for a solution using foreach"? If you are looking for a `standard` solution, it doesn't exist. – Ivan Stoev Dec 22 '15 at 11:18
  • Ok..thanks a lot @lvanStoev.. using for loop I already implemented that.. I am looking for, if its possible through foreach.. Thanks – Vikrant Mishra Dec 22 '15 at 11:21