概要
cscの作法、調べてみた。
練習問題やってみた。
練習問題
comboboxの、ValueMemberを検索して、SelectedIndexを設定せよ。
写真
サンプルコード
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;
Button button1;
DataTable dt;
public Form1() {
Text = "ComboBox";
ClientSize = new Size(200, 200);
Label label = new Label();
label.Location = new Point(10, 50);
label.Text = "フルーツ";
Controls.Add(label);
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, "キウイ");
comboBox1 = new ComboBox();
comboBox1.Location = new Point(30, 100);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "id";
comboBox1.SelectedIndex = -1;
comboBox1.SelectedValueChanged += comboBox1_TextChanged;
Controls.Add(comboBox1);
button1 = new Button();
button1.Text = "set";
button1.AutoSize = true;
button1.Dock = DockStyle.Bottom;
button1.BackColor = Color.Aqua;
button1.Click += new EventHandler(button1_Click);
this.Controls.Add(button1);
}
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 + ")");
}
private void button1_Click(object sender, EventArgs e) {
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow row = dt.Rows[i];
if (Convert.ToInt32(row["id"]) == 2)
comboBox1.SelectedIndex = i;
}
}
[STAThread]
public static void Main() {
Application.Run(new Form1());
}
}
}
以上。