最近在开发一套管理软件中,要对七、八个Textbox动态添加可以选择的组合框,点击文本框中先显示组合框Combox并且在组合框中异步加载数据,选择Combox数据,并自动将数据添加Textbox.text中,如果按照常规写法,可能需要更多的代码;
1 void Form1_Load(object sender, EventArgs e) 2 { 3 //对三个文本框添加事件 4 textBox1.Click += new EventHandler(textBox1_Click); 5 textBox2.Click += new EventHandler(textBox1_Click); 6 textBox3.Click += new EventHandler(textBox1_Click); 7 } 8 9 void textBox1_Click(object sender, EventArgs e) 10 { 11 //TODO:定义一个动态组合框 12 ComboBox cmb = new ComboBox(); 13 14 TextBox txtBox = sender as TextBox; 15 16 //用组合框来覆盖文本框 17 cmb.Location = txtBox.Location; 18 cmb.Size = txtBox.Size; 19 20 this.Controls.Add(cmb); 21 cmb.Visible = true; 22 //置前 23 cmb.BringToFront(); 24 25 //对组合框异步加载 26 ThreadPool.QueueUserWorkItem( 27 state => 28 this.BeginInvoke(new Action(() => 29 { cmb.Items.AddRange(new object[] {"one", "two", "three"}); }))); 30 31 //添加事件,使用匿名方法 32 cmb.SelectedIndexChanged += delegate 33 { 34 txtBox.Text = cmb.Text; 35 //置后 36 cmb.SendToBack(); 37 cmb = null; 38 }; 39 40 }