teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

ソース部分をマークダウン

2018/01/17 08:42

投稿

monagano
monagano

スコア246

answer CHANGED
@@ -1,18 +1,26 @@
1
1
  以下のように、列名を望む順番に並べたstring配列を作成し、添え字を振ってみてはどうでしょう。
2
+ ```C#
2
3
  foreach(var colNameIndex in new string[] { "Name", "Sex", "Age", "Like" }.Select((str, index) => new { str, index }))
3
- {
4
+ {
4
- this.dataGridView1.Columns[colNameIndex.str].DisplayIndex = colNameIndex.index;
5
+ this.dataGridView1.Columns[colNameIndex.str].DisplayIndex = colNameIndex.index;
5
- }
6
+ }
7
+ ```
6
8
  または
9
+ ```C#
7
10
  new string[] { "Name", "Sex", "Age", "Like" }.Select((str, index) => new { str, index }).ToList().ForEach(colNameIndex => this.dataGridView1.Columns[colNameIndex.str].DisplayIndex = colNameIndex.index);
11
+ ```
8
12
 
9
13
  リフレクションを使ってクラスのプロパティを参照して列名を取得することもできますが、並び順が保障されないため、InfoModelクラス側に手を加えてやる必要が生じます。
10
14
 
11
15
  列幅は、まとめて指定なら(例として20を指定)
16
+ ```C#
12
- foreach(DataGridViewColumn col in this.dataGridView1.Columns)
17
+ foreach(DataGridViewColumn col in this.dataGridView1.Columns)
13
- {
18
+ {
14
- col.Width = 20;
19
+ col.Width = 20;
15
- }
20
+ }
21
+ ```
16
22
  もしくは
23
+ ```C#
17
24
  this.dataGridView1.Columns.Cast<DataGridViewColumn>().ToList().ForEach(col=>col.Width=20);
25
+
18
- で良いと思います。
26
+ ```で良いと思います。