コンボボックスの選択処理

コンボボックスでの選択処理の実装を考える。選択項目がプルダウンメニューで表示され、その中の選んだ一つのみが画面に表示されるところが、リストボックスとは異なる。そのコンボボックスで項目を選択したときの処理をどう実装するかを示す。

  • 項目選択のイベント = SelectedIndexChanged
  • 選択項目の値の取得 = sender.Text

サンプルコードを以下に示す。

import System.Drawing
import System.Windows.Forms

from System.Drawing import *
from System.Windows.Forms import *

class MainForm(Form):
 def __init__(self):
  self.InitializeComponent()
 
 def InitializeComponent(self):
  self._label1 = System.Windows.Forms.Label()
  self._comboBox1 = System.Windows.Forms.ComboBox()
  self.SuspendLayout()
  #
  # label1
  #
  self._label1.Font = System.Drawing.Font("MS UI Gothic", 12, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 128)
  self._label1.Location = System.Drawing.Point(37, 138)
  self._label1.Name = "label1"
  self._label1.Size = System.Drawing.Size(235, 23)
  self._label1.TabIndex = 1
  self._label1.Text = """None is selected.
"""
  #
  # comboBox1
  #
  self._comboBox1.FormattingEnabled = True
  self._comboBox1.Items.AddRange(System.Array[System.Object](
   ["Car",
   "Truck",
   "OpenCar",
   "Taxi",
   "SportsCar",
   "MiniCar"]))
  self._comboBox1.Location = System.Drawing.Point(37, 49)
  self._comboBox1.Name = "comboBox1"
  self._comboBox1.Size = System.Drawing.Size(121, 20)
  self._comboBox1.TabIndex = 2
  self._comboBox1.SelectedIndexChanged += self.ComboBox1SelectedIndexChanged
  #
  # MainForm
  #
  self.ClientSize = System.Drawing.Size(284, 188)
  self.Controls.Add(self._comboBox1)
  self.Controls.Add(self._label1)
  self.Name = "MainForm"
  self.Text = "test"
  self.ResumeLayout(False)

 def ComboBox1SelectedIndexChanged(self, sender, e):
  self._label1.Text = sender.Text + " is selected."
  

実行結果を以下に示す。