winform 用户控件、 动态创建添加控件、timer控件、控件联动
用户控件:
相当于一个Panel 可以把多个控件放在里面 组合为一个控件,方便使用和布局。
动态创建添加控件
可以在一个大容器里一次性放入多个控件
例:根据文本框中输入的数字 给flowLayoutPanel1 添加多少个button
public Form2(haoyou hao) { InitializeComponent(); f = hao; } private void button1_Click(object sender, EventArgs e) { //先获取用户输入的是几 int count = Convert.ToInt32(textBox1.Text); flowLayoutPanel1.Controls.Clear(); //循环创建按钮,然后添加到容器中 for (int i = 1; i <= count; i++) { Button btn = new Button(); btn.Text = i.ToString(); flowLayoutPanel1.Controls.Add(btn); } }
timer控件
Timer控件主要会用到2个属性一个是Enabled和Interval
Enabled主要是控制当前Timer控件是否可用
timer1.Enabled=false;不可用
timer1.Enabled=true;可用
timer1.Interval=1000;主要是设置timer2_Tick事件的时间,单位为毫秒
例一:到9:00提示去上厕所
把timer2.Interval=60000;//1分钟
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
private void timer2_Tick(object sender, System.EventArgs e) { string cesuotime=DateTime.Now.DateTime.Now.ToShortTimeString();//得到现在的时间 if(cesuotime.equles("9:00")) { timer1.Enabled=false; MessageBox.show("该去上厕所了"); timer1.Enabled=true;//如果不先把enabled设置成false对话框会一直弹下去 } }
例二:每2小时提示用户看电脑时间已经很久了,需要休息了
把timer2.Interval=7200000;//7200秒
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
private void timer2_Tick(object sender, System.EventArgs e) { timer1.Enabled=false; MessageBox.show("需要休息了,开机已经2小时了"); timer1.Enabled=true;//如果不先把enabled设置成false对话框会一直弹下去 }
控件联动
通俗讲就是一个控件的属性变化引动另一控件也发生变化
例:使用3个comboBox选择 省市区
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using WindowsFormsApplication2.App_Code; namespace WindowsFormsApplication2 { public partial class Form2 : Form { public Form2() { InitializeComponent(); //绑定省 comboBox1.DataSource = new ChinaData().Select("0001"); comboBox1.DisplayMember = "AreaName"; comboBox1.ValueMember = "AreaCode"; //绑定市 comboBox2.DataSource = new ChinaData().Select(comboBox1.SelectedValue.ToString()); comboBox2.DisplayMember = "AreaName"; comboBox2.ValueMember = "AreaCode"; //绑定区县 comboBox3.DataSource = new ChinaData().Select(comboBox2.SelectedValue.ToString()); comboBox3.DisplayMember = "AreaName"; comboBox3.ValueMember = "AreaCode"; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { //绑定市 comboBox2.DataSource = new ChinaData().Select(comboBox1.SelectedValue.ToString()); comboBox2.DisplayMember = "AreaName"; comboBox2.ValueMember = "AreaCode"; } private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { //绑定区县 comboBox3.DataSource = new ChinaData().Select(comboBox2.SelectedValue.ToString()); comboBox3.DisplayMember = "AreaName"; comboBox3.ValueMember = "AreaCode"; } } }