如何动态加控件
我想在窗体上,动态地
首先,有一个文本框,有一个下拉框,需要当1文本框中有文字的时候,就动态在他后面出来一个下拉框
当然程序里也可以获取到这个下拉框和文本框的ID什么的
其实我就是想做一个动态的SQL语句的组合
就好像大家去搜索什么东西的时候,高级搜索界面里面的那些一样~
------解决方案--------------------给你这段,参考一下吧
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace eg42_addCtrlAtRuntimeApp
{
public partial class MainForm : Form
{
private int count;
public MainForm()
{
InitializeComponent();
}
void Btn_MouseEnter(object sender, EventArgs e)
{
Button currentButton = (Button)sender;
currentButton.BackColor = Color.Blue;
}
void Btn_MouseLeave(object sender, EventArgs e)
{
Button currentButton = (Button)sender;
currentButton.BackColor = System.Windows.Forms.Control.DefaultBackColor;
}
void Btn_Click(object sender, MouseEventArgs e)
{
Button currentButton = (Button)sender;
txt_msg.Text = "你点击了" + currentButton.Text;
}
void Btn_addButtonMouseClick(object sender, MouseEventArgs e)
{
count += 2; int localX = this.btn_addButton.Height * count; int localY = 10 * count;
Button toAddButton = new Button();
toAddButton.Name = "Button" + count;
toAddButton.Text = "按钮" + count + "";
toAddButton.Location = new Point(localX, localY);
toAddButton.MouseEnter += new EventHandler(this.Btn_MouseEnter);
toAddButton.MouseLeave += new EventHandler(this.Btn_MouseLeave);
toAddButton.MouseClick += new MouseEventHandler(this.Btn_Click);
this.Controls.Add(toAddButton);
}
}
}
------解决方案--------------------C# code
TextBox txtbox = new TextBox();
txtbox.Parent = this;
txtbox.Left = 0;
txtbox.Top = 0;
ComboBox combox = new ComboBox();
combox.Parent = this;
combox.Left = txtbox.Right + 10;
combox.Top = 0;
combox.Visible = false;
txtbox.Tag = combox;
txtbox.TextChanged += new EventHandler(
delegate(object obj, EventArgs ex)
{
((ComboBox)((TextBox)obj).Tag).Visible = !string.IsNullOrEmpty(((TextBox)obj).Text);
}
);
------解决方案--------------------
C# code
ComboBox cbo = new ComboBox();
cbo.DropDownStyle = ComboBoxStyle.DropDownList;
cbo.Location = new System.Drawing.Point(73, 171);
cbo.Name = "cboCont";
this.Controls.Add(cbo);
绑定combobox
------解决方案--------------------
有一个文本框,有一个下拉框,需要当1文本框中有文字的时候,就动态在他后面出来一个下拉框
完全不需要动态,动态的事件涉及到页面生命周期,很不好操作。
页面上隐藏掉下拉框。你只需要的文本框的TextChange事件判断,
if(!string.isnullorEmpty(text))
{
dropdownlist.visible = true; //设置下拉框显示。
}