« C# : ListBox を使った Drop、Collection、Filter の演習 | トップページ | C# : ListBox を使って「メニュー」サンプルコード作成 »

2012年7月14日 (土)

C# : ListBox の 表示文字、色。コレクションのソート、クエリ。

<目次はここです>

前回に引き続いてListBoxを使ったサンプルプログラムを作成しました。
Listbox20120714b_2

■演習内容
 ①java の ListCellRenderer に相当する処理
  ・ListBox に表示される文字を指定。 (例:ファイル名を表示)
  ・ファイル拡張子によって表示色を変更
  ・選択された時の背景色を設定

 ②コレクション
  ・ジェネリック
  ・ソート

 ③クエリ
  ・foreach(<T> x in collection){} の代わりにクエリ使用

 ④特殊フォルダ名取得
  ・MyDocuments      :
System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
  ・Currentフォルダ     :
Environment.CurrentDirectory
  ・フォフダ内のファイル一覧取得 :
Directory.GetFiles( @"C:\1_temp" )

Form1.Designer.cs

namespace Test20120714 {
    partial class Form1 {
        /// <summary>
        /// 必要なデザイナー変数です。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 使用中のリソースをすべてクリーンアップします。
        /// </summary>
        /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
        protected override void Dispose(bool disposing) {
            if (disposing && (components != null)) {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows フォーム デザイナーで生成されたコード

        /// <summary>
        /// デザイナー サポートに必要なメソッドです。このメソッドの内容を
        /// コード エディターで変更しないでください。
        /// </summary>
        private void InitializeComponent() {
            this.listBox1 = new System.Windows.Forms.ListBox();
            this.SuspendLayout();
            //
            // listBox1
            //
            this.listBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));

            this.listBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
            this.listBox1.FormattingEnabled = true;
            this.listBox1.ItemHeight = 12;
            this.listBox1.Location = new System.Drawing.Point(12, 19);
            this.listBox1.Name = "listBox1";
            this.listBox1.Size = new System.Drawing.Size(309, 148);
            this.listBox1.TabIndex = 0;

            this.listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem);
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(342, 197);
            this.Controls.Add(this.listBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

        }
        #endregion
        private System.Windows.Forms.ListBox listBox1;
    }
}

 

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;

namespace Test20120714 {
    public partial class Form1 : Form {

        public Form1() {
            InitializeComponent();
            setDummyData();
        }

        /// ダミーデータ追加
        private void setDummyData() {
            List<MyFile> list =
new List<MyFile>(); // Collection に Generics 使用
            listBox1.BeginUpdate();
            
foreach (string file in Directory.GetFiles(Environment.CurrentDirectory)) {
                list.Add(new MyFile(file));
            }
            
{// foreach の代わりに クエリを使用
            
   string myDocuments = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
               
var scoreQuery = from score in Directory.GetFiles(myDocuments) select new MyFile(score);
                list.AddRange(scoreQuery);
            }
          
list.Sort(CompareFile);  // ソート
            listBox1.
DataSource = list;
            listBox1.EndUpdate();
        }

        /// ソートで使用
        private int
CompareFile(MyFile f1, MyFile f2) {
            return f1.Extension.CompareTo(f2.Extension); 
// この例では拡張子でソート
        }

        /// DrawMode プロパティを DrawMode.OwnerDrawFixed または DrawMode.OwnerDrawVariable に設定
        /// ListBox1.DrawItem に  System.Windows.Forms.DrawItemEventHandler を追加

        private void listBox1
_DrawItem(object sender, DrawItemEventArgs e) {
            if (-1 == e.Index) {
// ListBoxが空のときにListBoxが選択されるとe.Indexが-1になる
                return;
            }
            object item = ((ListBox)sender).Items[e.Index];
            
Brush myBrush = Brushes.Black;                                            // デフォルトは黒色                
            if (item is MyFile) {
                MyFile p = ((MyFile)item);
                string ext = p.Extension;
                if (ext == ".xls" || ext == ".xlsx") {
                    myBrush = Brushes.Blue;
                } else if (ext == ".ppt") {
                    myBrush = Brushes.Violet;
                } else if (ext == ".jpg" || ext == ".jpeg" || ext == ".tiff" || ext == ".gif") {
                    myBrush = Brushes.LawnGreen;
                } else if (ext == ".exe") {
                    myBrush = Brushes.Red;
                }
            }
            e.DrawBackground();
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) {
   
             e.Graphics.FillRectangle(Brushes.Lavender, e.Bounds);  // 選択された Item の背景色設定
            }
            string txt = item is MyFile ? ((MyFile)item).FileName : item.ToString();
// ListBox に表示する文字列
            e.Graphics.DrawString(txt, e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
            e.DrawFocusRectangle(); // If the ListBox has focus, draw a focus rectangle around the selected item.

        }
    }

    /// ファイルを表すクラス
    class MyFile {
        private readonly string path;
        public string FileName { get; private set; } 
// ファイル名 (親パスを除く
        public string Extension { get; private set; }
// 拡張子

        public MyFile(string path) {
            this.path = path;
            FileName = Path.GetFileName(path);
            Extension = Path.GetExtension(path);
       }

        /// ListBox.Items.Contains()で使用
        public override bool
Equals(object obj) {
            if (obj == null || this.GetType() != obj.GetType()) {
                return false;
            } else {
                return this.path.Equals(((MyFile)obj).path);
            }
        }

        /// Equals で等しいと判断されるものは同じhashCodeを返す必要あり        
        public override int
GetHashCode() {
            return this.path.GetHashCode();
        }

        public override string ToString() {
            return FileName;
        }
    }
}

 

foreach List<MyFile> list = new List<MyFile>();
foreach (string file in Directory.GetFiles(@"C:\1_temp")) {
        list.
Add(new MyFile(file));
}
Query List<MyFile> list = new List<MyFile>();
var scoreQuery =
from score in Directory.GetFiles(@"C:\1_temp")
    
select new MyFile(score);
list.
AddRange(scoreQuery);
Query
+ラムダ式
List<MyFile> list = new List<MyFile>();
list.
AddRange(Directory.GetFiles(@"C:\1_temp").Select((n) => new MyFile(n)));

 

■Ref
 ・foreach(x in collection){}               msdn
 ・
演算子一覧                     msdn 。 3項演算子 string s = 0 < x ? "A":"B";

 ・ListBox.DrawItem イベント            msdn
 ・
ListBox.Sort メソッド                msdn
 ・
ListControl.DataSource プロパティ       msdn

 ・List.Sort メソッド (ジェネリック Comparison)  msdn
 ・
System.Collections.Generic 名前空間     msdn

« C# : ListBox を使った Drop、Collection、Filter の演習 | トップページ | C# : ListBox を使って「メニュー」サンプルコード作成 »

パソコン・インターネット」カテゴリの記事