- - PR -
コントロールをあたかも配列のように扱いたい
1
投稿者 | 投稿内容 | ||||
---|---|---|---|---|---|
|
投稿日時: 2003-07-03 16:53
VB6ではコントロールをコントロール配列として扱えましたが、
C#では扱えなくなってしまいました。 多くのコントロールをあたかも配列のように スマートに扱うにはどうすればよいでしょうか? 例えば textBox1.Text textBox2.Text … textBox50.Text これを text[0]="123"; text[1]="456"; string str = text[49]; のような感じで使いたいです。 環境 WindowsApplicationのフォーム(Form1) 言語 C# Q1.どのような方法がありますか? @インデクサ A参照型による間接的な参照 B他 Q2.具体的にclass Form1のどのセクションで定義、宣言、 初期化すればうまくいくのでしょうか? 注意 ここでいうコントロールはVB6のCOMではなくて C#標準のツールボックスにあるコントロール(みたいなもの) を想定しています。 (コントロールという呼び方は誤っているかも知れません) | ||||
|
投稿日時: 2003-07-03 17:58
KATSU System Designの鈴木です。
こんな方法でどうでしょうか? ちょっと長いですが全文載せます。 using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace WindowsApplication1 { public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.TextBox[] txtA; //コントロール配列 private System.ComponentModel.Container components = null; public Form1() { InitializeComponent(); txtA = new System.Windows.Forms.TextBox[5]; for (int i = 0; i < 5;i +=1) { txtA[i] = new System.Windows.Forms.TextBox(); //プロパティ設定 txtA[i].Text = (i+1).ToString(); txtA[i].BackColor = Color.White; txtA[i].BorderStyle = BorderStyle.Fixed3D; txtA[i].Size = new Size(100, 24); txtA[i].Location = new Point(10 + i * 120, 48); txtA[i].TextAlign = System.Windows.Forms.HorizontalAlignment.Right; //ベントハンドラに関連付け txtA[i].Click += new System.EventHandler(this.txtA_Click); } //フォーム上にコントロールを追加 this.Controls.AddRange(txtA); } public void txtA_Click(object sender, System.EventArgs e) { MessageBox.Show(((TextBox) sender).Text + "番目のTextBoxです"); } protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code private void InitializeComponent() { this.AutoScaleBaseSize = new System.Drawing.Size(5, 12); this.ClientSize = new System.Drawing.Size(608, 118); this.Name = "Form1"; this.Text = "Form1"; } #endregion /// <summary> /// アプリケーションのメイン エントリ ポイントです。 /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } } } | ||||
|
投稿日時: 2003-07-03 19:03
コレクションに入れてしまえばよいのではないでしょうか
| ||||
|
投稿日時: 2003-07-04 14:50
こんにちは。
ここの過去ログを、よく検索してください。いくつかでています。 具体的には、 1.自前で用意した配列に放り込む 2.コレクションに放り込む 3.名前の何文字目かを序数とし、検索する 4.専用のユーザコントロールを作成する という方法があがっています。 | ||||
|
投稿日時: 2003-07-05 00:24
ご返答ありがとうございます。
さっそく試してみました。 未だ、オブジェクト指向に慣れていないので、 キーワードだけでもわかれば本当に助かります。 |
1