WinForm的基础知识
MessageBox的几种常见用法
- 简单
MessageBox.Show("你确定想要删除吗?");
2. 增加上面提示标题
MessageBox.Show("你确定想要删除吗?", "提示");
3. 增加取消按钮
if (MessageBox.Show("你确定想要删除吗?", "提示",
MessageBoxButtons.OKCancel) == DialogResult.OK)
{
// delete
}
4. 增加图标
if (MessageBox.Show("你确定想要删除吗?", "提示", MessageBoxButtons.OKCancel,
MessageBoxIcon.Question) == DialogResult.OK)
{
//delete
}
5. 定义默认选择取消
if (MessageBox.Show("你确定想要删除吗?", "提示", MessageBoxButtons.OKCancel,
MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
== DialogResult.OK)
{
//delete
}
事件参数object sender, EventArgs e的理解
参数sender
sender表示触发事件的那个控件。若同一类控件处理方法相同,可以只写一个事件处理。(如:多个Button处理方法相同)就需要用到sender这个参数,这时需要把sender转换为相应类型的控件即可。
如:TextBox textbox = sender as TextBox;
例:四个Button单击,显示Button内容
private void button1_Click(object sender, EventArgs e)
{
Button mybtn = sender as Button;
MessageBox.Show(mybtn.Text);
}
参数e
e参数包含了事件所携带的信息,它用来辅助处理事件。
若e不是EventArgs 类本身,而是其子类(如:KeyPressEventArgs e),那么在写事件过程的时候往往会用到该对象e的属性或方法。如:e.Handled、 e.KeyChar。
例:控制文本框只能输入数字、.或退格键。
PS:e.Handled=true表示阻止输入字符, e.KeyChar表示用户输入的字符
private void txtNum_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9')
{
e.Handled = false; //不阻止,表示输入的是数字,则可以输入
}
else
{
if ((e.KeyChar == '.') || e.KeyChar == '\b')
{
e.Handled = false; //表示退格键或.可以输入
}
else
{
e.Handled = true; //其他阻止,即是不可以输入
}
}
}
遍历窗体控件
foreach (Control item in this.Controls)
{
if (item is TextBox) // 清空TextBox内容
{
item.Text = "";
}
if (item is RadioButton) // 重置RadioButton(选择男)
{
RadioButton r = (RadioButton)item;
r.Checked = false;
rdMale.Checked = true;
}
if (item is CheckBox) // 重置CheckBox
{
CheckBox ck = (CheckBox)item;
ck.Checked = false;
}
}
ListBox列表框常用属性
- Items属性
— Items .Add(object item) 向选项列表添加选项(添加一项)
—Items .AddRange(object[] items) 向选项列表添加选项(添加多项)
—Items .Remove(object value) 从集合中移除指定对象
—Items .RemoveAt(int index) 移除集合中指定索引的项
—Items .Insert(int index, object item) 向选项列表添加选项(添加到指定位置)
—Items .Clear() 清除列表框的所有项
—Items[int index] 获取或设置集合中指定索引处的项
—Items .Count() 获取集合中的项数
例:listBox1.Items.Add(“aa”);
例:listBox1.Items.AddRange(new string[] {“aa”, “bb”});
例:listBox1.Items.Remove(“aaa”);
例:listBox1.Items.RemoveAt(0);
例:listBox1.Items.Insert(1, “bbb”);
例:listBox1.Items.Clear();
例:listBox1.Items[0] --> “aaa”
例:listBox1.Items[0] = “aaa”;
例:listBox1.Items.Count(); --> 3
- SelectedItems属性
获取包含在当前选定的项的集合
—SelectedItems.Count 表示被选择的项目的数目
—SelectedItems[i] 根据指定索引获取被选择的项,即获取被选择的i项
例:listBox1.SelectedItems.Count // 10个里面选择了3个 则值为3
例:listBox1.SelectedItems[2] // 从被选择的3个里面,取第三个的值
- SelectedItem属性
获取或设置当前被选择的1项
例:listBox.SelectedItem // 获取选择中的第一项的值
例:listBox.SelectedItem = “aaa” // ????
- SelectedIndex
获取或设置选中项的索引(从0开始)
例:listBox.SelectedIndex --> 2 (选择了第3、5、6条数据)
例:listBox.SelectedIndex = 2 // 将第3条数据设置为选中状态
TreeView控件
—TreeNode tn1 = new TreeNode(string text, TreeNode[] children) 设置节点
—treeView1.Nodes.Add(string text / TreeNode node) 添加节点
—treeView1.SelectedNode.Level 获取深度
—treeView1.ExpandAll() 展开所有节点