LoginSignup
0
2

More than 1 year has passed since last update.

DataGridView.SelectedRowsの格納順序

Last updated at Posted at 2021-08-19

はじめに

DataGridViewのSelectedRowsってどういう順番に格納されているのかいまいちわからない。

Index SeqNo
1 00101
2 00102
3 00103
4 00104

というデータがあったときに、下から4番目、2番目、1番目という順番で選択した時とかね。

どういう順番に選択したとしてもGridの上から順番に処理がしたい!
と悩んでいた時に「SortedDictionaryクラスを使えばいいんじゃないか?」という天の声が。
※忘れたころに使うので備忘録として

SortedDictionaryって何?

SortedDictionary(Of TKey, TValue)
SortedDictionary<TKey, TValue>

で、TKeyの昇順に並び替えてくれるっぽい。

DataGridViewの行を複数選択した時、Gridの先頭から順番(昇順)にデータ(SeqNo)を取得したいので

TKey -> Index
TValue -> SeqNo

とすればいいのか。ふむ。なるほどな。

実装してみた

sample1.vb
Dim sortedDictionary As New SortedDictionary(Of Integer, Integer)
For Each dataGridViewRow As DataGridViewRow In DataGridView1.SelectedRows
    sortedDictionary.Add(dataGridViewRow.Index, dataGridViewRow.Cells("SeqNo").Value)
Next
sample1.cs
var sortedDictionary = new SortedDictionary<int, int>();
foreach (DataGridViewRow dataGridViewRow in dataGridView1.SelectedRows)
{
    sortedDictionary.Add(dataGridViewRow.Index, Convert.ToInt32(dataGridViewRow.Cells["SqlNo"].Value));
}

値の取り出し方はこんな感じ

sample2.vb
For Each kvp As KeyValuePair(Of Integer, Integer) In sortedDictionary
    Console.WriteLine(kvp.Value)
Next
sample2.cs
foreach (KeyValuePair<int, int> kvp in sortedDictionary)
{
    Console.WriteLine(kvp.Value);
}

なんか他にいい方法、記述がありそうだけどもね。

追記

Linqを使ってみよう。

sample3.vb
Dim query = From r As DataGridViewRow In dataGridView1.SelectedRows
            Order By r.Index
For Each r In query
    Console.WriteLine(r.Cells("SeqNo"))
Next
sample3.cs
var query = from DataGridViewRow r in dataGridView1.SelectedRows
            orderby r.Index
            select r;
foreach (DataGridViewRow r in query)
{
    Console.WriteLine(r.Cells["SeqNo"]);
}

なんかこっちのほうがすっきりするね。

0
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2