概要
cscの作法、調べてみた。
練習問題やってみた。
練習問題
ComboBoxで表示で、id とnameをくっつけて、表示する。
写真
サンプルコード
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Data;
namespace App
{
public partial class Form1: Form {
ComboBox comboBox1;
public Form1() {
Text = "ComboBox";
ClientSize = new Size(300, 300);
Label label = new Label();
label.Location = new Point(10, 50);
label.Text = "フルーツ";
Controls.Add(label);
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] {
new DataColumn("id", typeof(int)),
new DataColumn("name", typeof(string))
});
dt.Rows.Add(0, "");
dt.Rows.Add(1, "バナナ");
dt.Rows.Add(2, "マンゴー");
dt.Rows.Add(3, "パパイア");
dt.Rows.Add(4, "キウイ");
dt.Columns.Add("idname", typeof(string));
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["idname"] = dt.Rows[i]["id"].ToString() + " " + dt.Rows[i]["name"];
}
comboBox1 = new ComboBox();
comboBox1.Location = new Point(30, 100);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "idname";
comboBox1.ValueMember = "id";
comboBox1.SelectedIndex = -1;
comboBox1.SelectedValueChanged += comboBox1_TextChanged;
Controls.Add(comboBox1);
}
private void comboBox1_TextChanged(object sender, EventArgs e) {
int n = comboBox1.SelectedIndex;
string str = comboBox1.Text;
string str1 = comboBox1.SelectedValue.ToString();
MessageBox.Show("selected: " + n + " (" + str + ": " + str1 + ")");
}
[STAThread]
public static void Main() {
Application.Run(new Form1());
}
}
}
以上。