Timer组件介绍与使用
Timer组件 Timer计时器 间隔时间 ---每隔这个间隔时间就会引发事件
System.Windows.Forms.Timer Windows应用程序 独占一个线程 可以修改UI元素,基于UI的
- 属性 interval 时间间隔 ms 1000ms=1s
- 事件 tick
- 应用:动态时间显示
如果是Windows应用程序,要使用计时器功能,System.Windows.Forms.Timer 是首选。
如果单次执行时间超过间隔时间,会影响下次触发。精度很差。
Timers.Timer介绍
- System.Timers.Timer 基于服务 计时器 轻量
- 时间间隔 触发 Elapsed事件 ---执行操作 ----不是由UI线程执行的
- 不可以直接修改UI元素,可以通过UI元素的invoke()完成,委托里修改UI元素----修改UI元素
- 耗时操作,不会使UI失去响应 不会影响下一次的触发
- 停止?---stop
- Forms.Timer UI线程执行,可以直接修改UI元素
public partial class FrmTimer : Form
{
public FrmTimer()
{
InitializeComponent();
}
//每隔指定的时间间隔就会触发
private void timer1_Tick(object sender, EventArgs e)
{
lblDateTime.Text = DateTime.Now.ToString();
}
private void FrmTimer_Load(object sender, EventArgs e)
{
lblDateTime.Text = DateTime.Now.ToString();
timer1.Enabled = true;
System.Timers.Timer timer3 = new System.Timers.Timer();
timer3.Interval = 1000;
//timer3.AutoReset = false;//只会引发一次,就停止了
timer3.Elapsed += Timer3_Elapsed;
timer3.Start();
}
int count = 0;
private void Timer3_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//lblDt2.Text= DateTime.Now.ToString();
count += 1;
Action act = UpdateTime;
this.Invoke(act);
if(count >10)
{
System.Timers.Timer timer = (System.Timers.Timer)sender;
timer.Stop();
}
}
private void UpdateTime()
{
lblDt2.Text = DateTime.Now.ToString();
}
}
Threading.Timer介绍与使用
- System.Threading.Timer 多线程 计时器 轻量级 精度高
- 提供以指定的时间间隔对线程池线程执行方法的机制。
- 单次运行过长,并不会影响下次的触发, 回调方法执行操作
- 不可以直接修改UI元素,也不是由UI线程上运行,UI元素的invoke()来实现
public partial class FrmTimer : Form
{
public FrmTimer()
{
InitializeComponent();
}
//每隔指定的时间间隔就会触发
private void timer1_Tick(object sender, EventArgs e)
{
lblDateTime.Text = DateTime.Now.ToString();
}
System.Threading.Timer timer4;
private void FrmTimer_Load(object sender, EventArgs e)
{
//UI
lblDateTime.Text = DateTime.Now.ToString();
timer1.Enabled = true;
//服务
System.Timers.Timer timer3 = new System.Timers.Timer();
timer3.Interval = 1000;
//timer3.AutoReset = false;//只会引发一次,就停止了
timer3.Elapsed += Timer3_Elapsed;
timer3.Start();
//多线程
//period 时间间隔 0或-1 只会执行一 次,然后就停止
//Change 可以让计时器重新启动
//停止 period 0 -1 timer4.Dispose()
int count2 = 0;
timer4 = new System.Threading.Timer(new System.Threading.TimerCallback(o => {
count2 += 2;
Action<int> act = ShowCount;
this.Invoke(act, count2);
}), null, 1000,1000);
//timer4.Change(2000, 2000);//改变延迟启动时间和时间间隔
}
private void ShowCount(int cout)
{
txtCount.Text = cout.ToString();
if (cout > 50)
timer4.Dispose();
}
int count = 0;
private void Timer3_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//lblDt2.Text= DateTime.Now.ToString();
count += 1;
Action act = UpdateTime;
this.Invoke(act);
if(count >10)
{
System.Timers.Timer timer = (System.Timers.Timer)sender;
timer.Stop();
}
}
private void UpdateTime()
{
lblDt2.Text = DateTime.Now.ToString();
}
}
ProgressBar介绍与使用
ProgressBar控件 显示某个操作进度
介绍
属性 Value Step MarqueeAnimationSpeed ms Max Min Style
方法 PerformStep() Increment()
使用
结合Timer一起实现进度条加载过程---动态
public partial class FrmProgressBar : Form
{
public FrmProgressBar()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if(pbarData.Value<pbarData.Maximum)
{
// pbarData.PerformStep(); //针对Marquee样式,不能调用
pbarData.Value += pbarData.Step;//针对Marquee样式
lblValue.Text = pbarData.Value.ToString();
}
else
{
lblValue.Text = "加载完成!";
timer1.Stop();
}
}
/// <summary>
/// 加载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLoad_Click(object sender, EventArgs e)
{
if(txtMax.Text.Trim()!="")
{
int max = int.Parse(txtMax.Text.Trim());
pbarData.Maximum = max;
}
timer1.Start();
}
/// <summary>
/// Form Load
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FrmProgressBar_Load(object sender, EventArgs e)
{
pbarData.MarqueeAnimationSpeed = 1000;//滚动的速度
pbarData.Style = ProgressBarStyle.Marquee;//进度条样式
pbarData.Maximum = 100;//最大值
pbarData.Minimum = 0;
pbarData.Value = 0;//默认值
pbarData.Step = 5;//增量
}
/// <summary>
/// 暂停
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnPause_Click(object sender, EventArgs e)
{
timer1.Stop();
}
/// <summary>
/// 继续 重新启动计时器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnContinue_Click(object sender, EventArgs e)
{
timer1.Start();
}
}
ImageList介绍
ImageList控件 图片集合 用于存储图像资源,并在关联控件中显示出来
属性 Images 图像集合 同样大小的尺寸显示 每张图片 索引、键名
Images方法
- Add(Image/Icon)
- Add(string,Image/Icon)
- Contains(Image/String)
- IndexOf(Image/String)
- Remove(Image)
- RemoveAt(int)
- RemoveByKey(string)
- SetKeyName(int,string)
Images 都是动态添加
public partial class FrmImageList : Form
{
public FrmImageList()
{
InitializeComponent();
}
private void FrmImageList_Load(object sender, EventArgs e)
{
string path = @"D:\课件\录制课件\WF\WFFormUse\WFFormUse\Imgs";
if(Directory.Exists(path))
{
string[] files = Directory.GetFiles(path);
if(files.Length>0)
{
string[] fileType = { ".jpg", ".png" };
foreach (string fpath in files)
{
if(fileType.Contains(Path.GetExtension(fpath)))
{
Image img = Image.FromFile(fpath);
string keyName= Path.GetFileNameWithoutExtension(fpath);
imgList.Images.Add(keyName, img);//添加
}
}
imgList.ImageSize = new Size(30, 30);
//label1.ImageIndex = 2;
label1.ImageKey = "03-hu";
}
}
}
}
ListView介绍
属性
- ShowGroups Groups 组集合 Items 项的集合 MultiSelect
- SmallImageList 除大图标视图以外的所有视图图像的ImageList控件
- 详细:AllowColumnRecorder Columns GridLine 网格
- Large AutoArrange LargeImageList
- SmallIcon AutoArrange
- Tile
- CheckedIndices CheckedItems SelectedIndices SelectedItems
事件 SelectedIndexChanged ColumnClick ItemChecked
public partial class FrmListView2 : Form
{
public FrmListView2()
{
InitializeComponent();
}
private void FrmListView2_Load(object sender, EventArgs e)
{
LoadImgList();
lvList.Items.Clear();
lvList.ShowGroups = false;
if(largeList!=null && largeList.Images.Count >0)
{
for(int i=0;i<largeList.Images.Count;i++)
{
string iText = largeList.Images.Keys[i];
ListViewItem li = new ListViewItem();
li.Text = iText;
li.ImageIndex =i;
lvList.Items.Add(li);
}
}
lvList.View = View.LargeIcon;
lvList.LargeImageList = largeList;
lvList.SmallImageList = smallList;
}
Dictionary<int, string> dic = new Dictionary<int, string>();
private void LoadImgList()
{
string path = @"D:\课件\录制课件\WF\WFFormUse\WFFormUse\Imgs";
if (Directory.Exists(path))
{
string[] files = Directory.GetFiles(path);
if (files.Length > 0)
{
largeList.Images.Clear();
smallList.Images.Clear();
int index = 0;
string[] fileType = { ".jpg", ".png" };
foreach (string fpath in files)
{
if (fileType.Contains(Path.GetExtension(fpath)))
{
Image img = Image.FromFile(fpath);
string key = Path.GetFileNameWithoutExtension(fpath);
largeList.Images.Add(key,img);
smallList.Images.Add(key,img);
dic.Add(index, fpath);
index++;
}
}
largeList.ImageSize = new Size(50, 50);
smallList.ImageSize= new Size(20, 20);
}
}
}
}
ListView应用
任务:
- 大图标 最大化图标,下面显示文本标签
- 小图标 小图标,右边显示文本标签
- List 小图标,右边显示文本标签,各项排列在列中,没有列标头
- Tile视图 最大化图标(使用其它操作系统,不清楚),文本显示右边,如果还有其它子项信息,也是显示在右边。
- 详细信息视图
- 分列显示,第一列显示:小图标,右边文本,其他列只显示文本,有列标头
public partial class FrmListView2 : Form
{
public FrmListView2()
{
InitializeComponent();
}
private void FrmListView2_Load(object sender, EventArgs e)
{
LoadImgList();
lvList.Items.Clear();
lvList.ShowGroups = false;//是否分组显示
if(largeList!=null && largeList.Images.Count >0)
{
for(int i=0;i<largeList.Images.Count;i++)
{
string iText = largeList.Images.Keys[i];
//添加ListView控件中的项
ListViewItem li = new ListViewItem();
li.Text = iText;
li.ImageIndex =i;
lvList.Items.Add(li);
}
}
lvList.View = View.LargeIcon;//指定视图模式
lvList.LargeImageList = largeList;//大图标使用的ImageList
lvList.SmallImageList = smallList;//除大图标以外所有视图使用的ImageList
}
Dictionary<int, string> dic = new Dictionary<int, string>();
//加载图片集合
private void LoadImgList()
{
string path = @"D:\课件\录制课件\WF\WFFormUse\WFFormUse\Imgs";
if (Directory.Exists(path))
{
string[] files = Directory.GetFiles(path);
if (files.Length > 0)
{
largeList.Images.Clear();
smallList.Images.Clear();
int index = 0;
string[] fileType = { ".jpg", ".png" };
foreach (string fpath in files)
{
if (fileType.Contains(Path.GetExtension(fpath)))
{
Image img = Image.FromFile(fpath);
string key = Path.GetFileNameWithoutExtension(fpath);
largeList.Images.Add(key,img);
smallList.Images.Add(key,img);
dic.Add(index, fpath);
index++;
}
}
//图片尺寸
largeList.ImageSize = new Size(50, 70);
smallList.ImageSize= new Size(20, 20);
}
}
}
//大图标视图
private void btnLarge_Click(object sender, EventArgs e)
{
lvList.View = View.LargeIcon;
}
//小图标视图
private void btnSmall_Click(object sender, EventArgs e)
{
lvList.View = View.SmallIcon;
}
//列表视图
private void btnList_Click(object sender, EventArgs e)
{
lvList.View = View.List;
}
//Tile视图 它的图标也使用的是LargeList 图片集合控件中的图片
private void btnTile_Click(object sender, EventArgs e)
{
lvList.View = View.Tile;
}
//详细信息视图 列
private void btnDetails_Click(object sender, EventArgs e)
{
lvList.Items.Clear();
lvList.Columns.Clear();
lvList.ShowGroups = false;
lvList.View = View.Details;//设置详细信息视图
//列的添加
lvList.Columns.Add("文件名", 100, HorizontalAlignment.Left);
lvList.Columns.Add("创建日期", 150, HorizontalAlignment.Left);
lvList.Columns.Add("类型", 80, HorizontalAlignment.Left);
lvList.Columns.Add("大小", 60, HorizontalAlignment.Left);
//项
for (int i = 0; i < dic.Count; i++)
{
ListViewItem li = new ListViewItem();
li.ImageIndex = i;
li.Text = smallList.Images.Keys[i];
li.SubItems.Add(File.GetCreationTime(dic[i]).ToString());//创建日期
li.SubItems.Add(Path.GetExtension(dic[i]));//类型
long length = new FileInfo(dic[i]).Length;//获取文件大小 B
li.SubItems.Add((length / 1024).ToString());//KB
lvList.Items.Add(li);
}
lvList.GridLines = true;//显示网格
}
}
ListView分组
ListView分组显示
项添加时,没有考虑分组,取名却包含分组
方案:判断名称,编号,将这项分到这一组 ----目的
建立分组关系:组名---编号
关系存储起来,分组时,就以这个关系为准。
List视图 不支持分组显示
public partial class FrmListView2 : Form
{
public FrmListView2()
{
InitializeComponent();
}
Dictionary<string, string> dicGroup = new Dictionary<string, string>();
private void FrmListView2_Load(object sender, EventArgs e)
{
LoadImgList();
//初始化分组信息
lvList.Groups.Clear();
lvList.Groups.Add(new ListViewGroup("花", HorizontalAlignment.Center));
lvList.Groups.Add(new ListViewGroup("动物", HorizontalAlignment.Center));
lvList.Groups.Add(new ListViewGroup("人物", HorizontalAlignment.Center));
lvList.Groups.Add(new ListViewGroup("风景", HorizontalAlignment.Center));
lvList.Items.Clear();
//关系存储
dicGroup.Add("花", "04");
dicGroup.Add("动物", "01");
dicGroup.Add("人物", "02");
dicGroup.Add("风景", "03");
lvList.ShowGroups = false;//是否分组显示
if (largeList!=null && largeList.Images.Count >0)
{
for(int i=0;i<largeList.Images.Count;i++)
{
string iText = largeList.Images.Keys[i];
//添加ListView控件中的项
ListViewItem li = new ListViewItem();
li.Text = iText;
li.ImageIndex =i;
lvList.Items.Add(li);
}
}
lvList.View = View.LargeIcon;//指定视图模式
lvList.LargeImageList = largeList;//大图标使用的ImageList
lvList.SmallImageList = smallList;//除大图标以外所有视图使用的ImageList
}
Dictionary<int, string> dic = new Dictionary<int, string>();
//加载图片集合
private void LoadImgList()
{
string path = @"D:\课件\录制课件\WF\WFFormUse\WFFormUse\Imgs";
if (Directory.Exists(path))
{
string[] files = Directory.GetFiles(path);
if (files.Length > 0)
{
largeList.Images.Clear();
smallList.Images.Clear();
int index = 0;
string[] fileType = { ".jpg", ".png" };
foreach (string fpath in files)
{
if (fileType.Contains(Path.GetExtension(fpath)))
{
Image img = Image.FromFile(fpath);
string key = Path.GetFileNameWithoutExtension(fpath);
largeList.Images.Add(key,img);
smallList.Images.Add(key,img);
dic.Add(index, fpath);
index++;
}
}
//图片尺寸
largeList.ImageSize = new Size(50, 70);
smallList.ImageSize= new Size(20, 20);
}
}
}
//大图标视图
private void btnLarge_Click(object sender, EventArgs e)
{
lvList.View = View.LargeIcon;
}
//小图标视图
private void btnSmall_Click(object sender, EventArgs e)
{
lvList.View = View.SmallIcon;
}
//列表视图
private void btnList_Click(object sender, EventArgs e)
{
lvList.View = View.List;
}
//Tile视图 它的图标也使用的是LargeList 图片集合控件中的图片
private void btnTile_Click(object sender, EventArgs e)
{
lvList.View = View.Tile;
}
//详细信息视图 列
private void btnDetails_Click(object sender, EventArgs e)
{
lvList.Items.Clear();
lvList.Columns.Clear();
//lvList.ShowGroups = false;
lvList.View = View.Details;//设置详细信息视图
//列的添加
lvList.Columns.Add("文件名", 100, HorizontalAlignment.Left);
lvList.Columns.Add("创建日期", 150, HorizontalAlignment.Left);
lvList.Columns.Add("类型", 80, HorizontalAlignment.Left);
lvList.Columns.Add("大小", 60, HorizontalAlignment.Left);
//项
for (int i = 0; i < dic.Count; i++)
{
ListViewItem li = new ListViewItem();
li.ImageIndex = i;
li.Text = smallList.Images.Keys[i];
li.SubItems.Add(File.GetCreationTime(dic[i]).ToString());//创建日期
li.SubItems.Add(Path.GetExtension(dic[i]));//类型
long length = new FileInfo(dic[i]).Length;//获取文件大小 B
li.SubItems.Add((length / 1024).ToString());//KB
if(lvList.ShowGroups)
{
foreach (ListViewGroup lvg in lvList.Groups)
{
//判断项文本的前面的编号是否与组所对应的编号一致,如果一致,就将该项分到这一组
if (li.Text.Substring(0, 2) == dicGroup[lvg.Header])
{
li.Group = lvg;//设置项所属的组
break;
}
}
}
lvList.Items.Add(li);
}
lvList.GridLines = true;//显示网格
}
//分组
private void btnGroup_Click(object sender, EventArgs e)
{
lvList.ShowGroups = true;
GroupShow();
}
//项分组处理
private void GroupShow()
{
for (int i = 0; i < lvList.Items.Count; i++)
{
foreach (ListViewGroup lvg in lvList.Groups)
{
//判断项文本的前面的编号是否与组所对应的编号一致,如果一致,就将该项分到这一组
if (lvList.Items[i].Text.Substring(0, 2) == dicGroup[lvg.Header])
{
lvList.Items[i].Group = lvg;//设置项所属的组
break;
}
}
}
}
}
MenuStrip介绍
MenuStrip介绍 菜单控件----包含多个菜单项的容器
属性 Name Dock Items 菜单项的集合
Items
项 ToolStripMenuItem
ShortcutKeys快捷键 Alt+F 同时 项文本后面(&F)
Ctrl+N
DropDownItems 子菜单集合
子菜单项 ToolStripMenuItem
菜单项中图标---关联图片集合控件ImageList
MenuStrip菜单响应及代码添加菜单项
1.菜单项响应 ----注册菜单项Click事件
手动添加---每个菜单项,都要为它注册响应--Click
菜单项它有子级菜单,就不用为它注册响应
2.代码添加菜单项及响应
Load事件里,代码添加
public partial class FrmMenuStrip : Form
{
public FrmMenuStrip()
{
InitializeComponent();
}
private void FrmMenuStrip_Load(object sender, EventArgs e)
{
//代码添加菜单项
ToolStripMenuItem miStudent = new ToolStripMenuItem();
miStudent.Name = "miStudent";
miStudent.Text = "学生管理(&M)";
//它下面还有子菜单
ToolStripMenuItem miAddStudent = new ToolStripMenuItem();
miAddStudent.Name = "miAddStudent";
miAddStudent.Text = "新增学生";
miAddStudent.Click += MiAddStudent_Click;
miStudent.DropDownItems.Add(miAddStudent);//添加子菜单
StudentMenus.Items.Add(miStudent); //添加主菜单
}
private void MiAddStudent_Click(object sender, EventArgs e)
{
MForms.FrmAddStudent fAddStudent = new MForms.FrmAddStudent();
fAddStudent.MdiParent = this;//设置当前窗体的父窗体
fAddStudent.Show();//Mdi容器不支持ShowDialog()
}
//退出系统
private void miExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
//新增学生
private void miAddStudent_Click(object sender, EventArgs e)
{
MForms.FrmAddStudent fAddStudent = new MForms.FrmAddStudent();
fAddStudent.MdiParent = this;//设置当前窗体的父窗体
fAddStudent.Show();//Mdi容器不支持ShowDialog()
}
//新增班级
private void miAddClass_Click(object sender, EventArgs e)
{
MForms.FrmAddClass fAddClass = new MForms.FrmAddClass();
fAddClass.MdiParent = this;
fAddClass.Show();
}
}
ContextMenuStrip介绍
ContextMenuStrip控件 右键菜单
- 1.介绍
- 2.属性
- 3.使用 依赖某个窗体或控件的。
public partial class FrmContextMenuStrip : Form
{
public FrmContextMenuStrip()
{
InitializeComponent();
}
//设置背景色为红色
private void miRed_Click(object sender, EventArgs e)
{
this.BackColor = Color.Red;
}
//设置背景色为绿色
private void miGreen_Click(object sender, EventArgs e)
{
this.BackColor = Color.Green;
}
private void miAddStudent_Click(object sender, EventArgs e)
{
MForms.FrmAddStudent fStudent = new MForms.FrmAddStudent();
fStudent.Show();
}
private void miForeColor_Click(object sender, EventArgs e)
{
button1.ForeColor = Color.Blue;
}
private void FrmContextMenuStrip_Load(object sender, EventArgs e)
{
menuStrip1.Items[0].MouseHover += FrmContextMenuStrip_MouseHover;
}
private void FrmContextMenuStrip_MouseHover(object sender, EventArgs e)
{
if (sender is ToolStripDropDownItem)
{
ToolStripDropDownItem item = sender as ToolStripDropDownItem;
if (item.HasDropDownItems && !item.DropDown.Visible)
{
item.ShowDropDown();
}
}
}
}
ToolStrip介绍
ToolStrip 紧接菜单栏之下,工具栏
介绍
- 属性 Item 如果要设置项中图片与文本的显示的方式,设置DisplayStyle
- ToolStripButton 按钮 响应事件:Click
- ToolStripLabel 标签 Click
- ToolStripSplitButton 拆分按钮 ButtonClick 点击拆分按钮的按钮部分 点击下拉项 Click
- ToolStripDropDownButton 下拉按钮 DropDownItemClicked 点击下拉项
- ToolStripComboBox 下拉组合框 SelectedIndexChanged
- ToolStripTextBox 文本输入框 TextChanged
- ToolStripProgressBar 进度条 没有特有的事件, 一般不会去注册事件
StatusStrip介绍
介绍 账号 角色信息 操作位置信息 进度条 版本信息
属性 Dock:bottom Items
使用 做什么---账号 角色信息 操作位置信息 进度条 版本信息
public partial class FrmStatusStrip : Form
{
public FrmStatusStrip()
{
InitializeComponent();
}
private void FrmStatusStrip_Load(object sender, EventArgs e)
{
tsslblUserInfo.Text = "admin,欢迎访问管理系统!";
tsslblBanQuan.Text = "管理系统V 1.0";
}
}
partial class FrmStatusStrip
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmStatusStrip));
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.tsslblUserInfo = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripProgressBar1 = new System.Windows.Forms.ToolStripProgressBar();
this.toolStripDropDownButton1 = new System.Windows.Forms.ToolStripDropDownButton();
this.toolStripSplitButton1 = new System.Windows.Forms.ToolStripSplitButton();
this.tsslblBanQuan = new System.Windows.Forms.ToolStripStatusLabel();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.statusStrip1.SuspendLayout();
this.SuspendLayout();
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsslblUserInfo,
this.toolStripProgressBar1,
this.toolStripDropDownButton1,
this.toolStripSplitButton1,
this.tsslblBanQuan});
this.statusStrip1.Location = new System.Drawing.Point(0, 371);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(546, 22);
this.statusStrip1.TabIndex = 0;
this.statusStrip1.Text = "statusStrip1";
//
// tsslblUserInfo
//
this.tsslblUserInfo.Name = "tsslblUserInfo";
this.tsslblUserInfo.Size = new System.Drawing.Size(0, 17);
//
// toolStripProgressBar1
//
this.toolStripProgressBar1.Name = "toolStripProgressBar1";
this.toolStripProgressBar1.Size = new System.Drawing.Size(100, 16);
//
// toolStripDropDownButton1
//
this.toolStripDropDownButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripDropDownButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripDropDownButton1.Image")));
this.toolStripDropDownButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripDropDownButton1.Name = "toolStripDropDownButton1";
this.toolStripDropDownButton1.Size = new System.Drawing.Size(29, 20);
this.toolStripDropDownButton1.Text = "toolStripDropDownButton1";
//
// toolStripSplitButton1
//
this.toolStripSplitButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripSplitButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripSplitButton1.Image")));
this.toolStripSplitButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripSplitButton1.Name = "toolStripSplitButton1";
this.toolStripSplitButton1.Size = new System.Drawing.Size(32, 20);
this.toolStripSplitButton1.Text = "toolStripSplitButton1";
//
// tsslblBanQuan
//
this.tsslblBanQuan.Name = "tsslblBanQuan";
this.tsslblBanQuan.Size = new System.Drawing.Size(0, 17);
//
// FrmStatusStrip
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(546, 393);
this.Controls.Add(this.statusStrip1);
this.Name = "FrmStatusStrip";
this.Text = "FrmStatusStrip";
this.Load += new System.EventHandler(this.FrmStatusStrip_Load);
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripStatusLabel tsslblUserInfo;
private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar1;
private System.Windows.Forms.ToolStripDropDownButton toolStripDropDownButton1;
private System.Windows.Forms.ToolStripSplitButton toolStripSplitButton1;
private System.Windows.Forms.ToolStripStatusLabel tsslblBanQuan;
private System.Windows.Forms.Timer timer1;
}
GroupBox、Panel介绍
分组容器的分组 标题 边框 滚动条 应用
GroupBox 为其他控件提供可识别的分组 Text 有边框 没有 按功能分组
Panel 将其他控件集中显示到一个面板中,集中管理
没有标题 默认没有 有滚动条 布局(分块)时使用
但可以设置 AutoScroll dock
可以呈放其他控件的容器
共同点:分组 容器 拖动Panel GroupBox 就会使它里边的控件一起移动
TabControl控件介绍
TabControl
- 介绍 管理一个TabPages集合 分组显示 每个Tabpage ---容器控件
- 属性 MultiLine TabPages Alignment Appearance ImageList
- 事件 SelectedIndexChanged 切换选项卡时发生
- 使用 一个模块有多个子页面,TabControl控件进行页面间快速切换。
public partial class FrmTabControl : Form
{
public FrmTabControl()
{
InitializeComponent();
}
private void FrmTabControl_Load(object sender, EventArgs e)
{
//tabControl1.SelectTab(1);//选中选项卡
//TabPage page = tabControl1.SelectedTab;//获取选中的选项卡
tabControl1.SelectedIndex = 1;//设置选中的选项卡
int count = tabControl1.TabCount; //选项卡的数目
}
//SelectedIndex属性值改变时触发
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
// MessageBox.Show(tabControl1.SelectedTab.Text);
string tpName = tabControl1.SelectedTab.Name;
switch(tpName)
{
case "tabPage1":
{
txtName.Text = "admin";
break;
}
case "tabPage2":
{
txtPwd.Text = "123456";
break;
}
}
}
}
SplitContainer介绍
介绍 将页面拆分成两个大小可调整的区域,中间有一个拆分条,拖动拆分条来调整左右区域的大小
属性
- FixedPanel 调整控件大小时,某个面板宽度保持不变
- Dock 默认 Fill
- IsSplitterFixed 拆分条是否固定 false
- Orientation 决定拆分器是水平还是垂直的 Vertical
- Panel1
- Panel2
- SplitterDistance 拆分条与左边或上边的距离 px
- SplitterWidth 拆分条的粗细
- SplitterIncrement 拆分条移动时的增量 px
partial class FrmSplitContainer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.spContainer = new System.Windows.Forms.SplitContainer();
this.spLeft = new System.Windows.Forms.SplitContainer();
this.spRight = new System.Windows.Forms.SplitContainer();
this.spRight2 = new System.Windows.Forms.SplitContainer();
this.spRight3 = new System.Windows.Forms.SplitContainer();
((System.ComponentModel.ISupportInitialize)(this.spContainer)).BeginInit();
this.spContainer.Panel1.SuspendLayout();
this.spContainer.Panel2.SuspendLayout();
this.spContainer.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.spLeft)).BeginInit();
this.spLeft.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.spRight)).BeginInit();
this.spRight.Panel2.SuspendLayout();
this.spRight.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.spRight2)).BeginInit();
this.spRight2.Panel2.SuspendLayout();
this.spRight2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.spRight3)).BeginInit();
this.spRight3.SuspendLayout();
this.SuspendLayout();
//
// spContainer
//
this.spContainer.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.spContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.spContainer.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.spContainer.Location = new System.Drawing.Point(0, 0);
this.spContainer.Name = "spContainer";
//
// spContainer.Panel1
//
this.spContainer.Panel1.Controls.Add(this.spLeft);
//
// spContainer.Panel2
//
this.spContainer.Panel2.Controls.Add(this.spRight);
this.spContainer.Size = new System.Drawing.Size(640, 363);
this.spContainer.SplitterDistance = 147;
this.spContainer.SplitterIncrement = 10;
this.spContainer.TabIndex = 0;
//
// spLeft
//
this.spLeft.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.spLeft.Dock = System.Windows.Forms.DockStyle.Fill;
this.spLeft.Location = new System.Drawing.Point(0, 0);
this.spLeft.Name = "spLeft";
this.spLeft.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.spLeft.Size = new System.Drawing.Size(147, 363);
this.spLeft.SplitterDistance = 156;
this.spLeft.TabIndex = 0;
//
// spRight
//
this.spRight.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.spRight.Dock = System.Windows.Forms.DockStyle.Fill;
this.spRight.Location = new System.Drawing.Point(0, 0);
this.spRight.Name = "spRight";
//
// spRight.Panel2
//
this.spRight.Panel2.Controls.Add(this.spRight2);
this.spRight.Size = new System.Drawing.Size(489, 363);
this.spRight.SplitterDistance = 343;
this.spRight.TabIndex = 0;
//
// spRight2
//
this.spRight2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.spRight2.Dock = System.Windows.Forms.DockStyle.Fill;
this.spRight2.Location = new System.Drawing.Point(0, 0);
this.spRight2.Name = "spRight2";
this.spRight2.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// spRight2.Panel2
//
this.spRight2.Panel2.Controls.Add(this.spRight3);
this.spRight2.Size = new System.Drawing.Size(142, 363);
this.spRight2.SplitterDistance = 101;
this.spRight2.TabIndex = 0;
//
// spRight3
//
this.spRight3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.spRight3.Dock = System.Windows.Forms.DockStyle.Fill;
this.spRight3.Location = new System.Drawing.Point(0, 0);
this.spRight3.Name = "spRight3";
this.spRight3.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.spRight3.Size = new System.Drawing.Size(142, 258);
this.spRight3.SplitterDistance = 105;
this.spRight3.TabIndex = 0;
//
// FrmSplitContainer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoScroll = true;
this.ClientSize = new System.Drawing.Size(640, 363);
this.Controls.Add(this.spContainer);
this.Name = "FrmSplitContainer";
this.Text = "FrmSplitContainer";
this.spContainer.Panel1.ResumeLayout(false);
this.spContainer.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.spContainer)).EndInit();
this.spContainer.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.spLeft)).EndInit();
this.spLeft.ResumeLayout(false);
this.spRight.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.spRight)).EndInit();
this.spRight.ResumeLayout(false);
this.spRight2.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.spRight2)).EndInit();
this.spRight2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.spRight3)).EndInit();
this.spRight3.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.SplitContainer spContainer;
private System.Windows.Forms.SplitContainer spLeft;
private System.Windows.Forms.SplitContainer spRight;
private System.Windows.Forms.SplitContainer spRight2;
private System.Windows.Forms.SplitContainer spRight3;
}
DataGridView介绍
- AllowUserToAddRows 是否向用户显示用于添加行的选项。False 不显示这个空白行。
- True 显示,并且可以这在行里输入数据,输入时,自动再添加一行空白行,输入完毕,回车,数据就添加到控件里了。
- AllowUserToAddRows 是否允许用户从DataGridView中删除行,默认true.用户可以选中某行,按Delete键就可以删除这行。
- AllowUserToOrderColumns False 是否启用手动列重新放置。若为true,可以手动调整列的放置,false时是不可以拖动列重新放置的。
- AllowUserToResizeColumns 是否可以调整列的大小 true
- AllowUserToResizeRows 是否可以调整行的大小 true
- AutoSizeColumnsMode 确定可见列的自动调整大小模式。None 一般调整为Fill
- AutoSizeRowsMode 确定可见行的自动调整大小模式。None
- *Columns 控件的列的集合
- *DataSource DataGridView控件的数据源
- EditMode 单元格编辑启动方式模式 EditOnKeyStrokeOrF2 键盘输入或F2,鼠标点击也行
- GridColor 单元格网络线的颜色
- MultiSelect True 用户一次是否可以选择多个单元格、行或列。
- SelectionMode RowHeaderSelect 如何选择单元格,一般设置为FullRowSelect
- *Rows 控件的所有行的集合
控件中的单元格:DataGridViewCell类
控件中的列:DataGridViewColumn类
控件中的行:DataGridViewRow类
行集合:DataGridViewRowCollection -----DataGridViewRow集合
列集合:DataGridViewColumnCollection -----DataGridViewColumn集合
列:DataGridViewColumn 属性:
Name 列对象的名称
ColumnType 列的类型 默认 DataGridViewTextBoxColumn
类型有: DataGridViewButtonColumn DataGridViewComboBoxColumn
DataGridViewImageColumn DataGridViewCheckBoxColumn
DataGridViewLinkColumn DataGridViewTextBoxColumn
DataPropertyName 该列绑定到数据源的属性名或数据库中的列名
HeaderText 列标题显示的文本
行:DataGridViewRow属性:
- DataBoundItem 获取用于填充行的数据绑定对象
- Selected 该行是否被选定
- State 该行的状态 DataGridViewElementStates
- Cells 该行的单元格集合
单元格:DataGridViewCell 属性
- Value 单元格的值 Selected 是否被选中
- RowIndex 所在行的行索引 OwningRow 所属的行
- OwningColumn 所属的列 ColumnIndex 所在列的索引
- FormattedValue 获取为显示进行格式化的单元格的值。
- FormattedValueType 格式化值的类型
- ValueType 单元格值的数据类型
1.常用事件
- 单击单元格任意部分发生 CellClick
- 单击单元格内容部分发生 CellContentClick
- 单元格里的值改变时发生 CellValueChanged 失去焦点时触发 ----即时触发?
- 通过CurrentCellDirtyStateChanged 单元格的状态因其内容更改而更改时发生
2 代码手动添加列、行
public partial class FrmDataGridView : Form
{
public FrmDataGridView()
{
InitializeComponent();
}
private void FrmDataGridView_Load(object sender, EventArgs e)
{
//添加列
DataGridViewColumn col1 = new DataGridViewCheckBoxColumn();
col1.Name = "colChk";
col1.HeaderText = "选择";
dgvUserNew.Columns.Add(col1);
DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn();
col2.Name = "colId";
col2.HeaderText = "编号";
dgvUserNew.Columns.Add(col2);
DataGridViewTextBoxColumn col3 = new DataGridViewTextBoxColumn();
col3.Name = "colUserName";
col3.HeaderText = "姓名";
dgvUserNew.Columns.Add(col3);
DataGridViewLinkColumn col4 = new DataGridViewLinkColumn();
col4.Name = "colDel";
col4.HeaderText = "删除";
dgvUserNew.Columns.Add(col4);
//添加数据 行
DataGridViewRow dr = new DataGridViewRow();
DataGridViewCell cell1 = new DataGridViewCheckBoxCell();
cell1.Value = false;
DataGridViewCell cell2 = new DataGridViewTextBoxCell();
cell2.Value = 1;
DataGridViewCell cell3 = new DataGridViewTextBoxCell();
cell3.Value = "admin";
DataGridViewCell cell4 = new DataGridViewLinkCell();
cell4.Value = "删除";
dr.Cells.Add(cell1);
dr.Cells.Add(cell2);
dr.Cells.Add(cell3);
dr.Cells.Add(cell4);
dgvUserNew.Rows.Add(dr);
}
private void dgvUsers_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
//MessageBox.Show(e.RowIndex.ToString());
}
//即时触发CellValueChanged事件
private void dgvUsers_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
//当前单元格是否有未提交的更改
if(dgvUsers.IsCurrentCellDirty)
{
dgvUsers.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
//点击单元格内容时发生
private void dgvUsers_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCell cell = dgvUsers.Rows[e.RowIndex].Cells[e.ColumnIndex];
if(cell.FormattedValue.ToString()=="删除")
{
MessageBox.Show("删除");
}
else if(cell.FormattedValue.ToString() == "修改")
{
MessageBox.Show("修改");
}
}
}
DataGridView绑定数据
DataGridView绑定数据源
DataSource --- DataTable\\\ List列表
public partial class FrmDataGridView : Form
{
public FrmDataGridView()
{
InitializeComponent();
}
private void FrmDataGridView_Load(object sender, EventArgs e)
{
// string sql = "select UserId,UserName,Age from UserInfos";
//string sql = "select UserId 编号,UserName 姓名,Age 年龄 from UserInfos";
string sql = "select * from UserInfos";
//获取数据
DataTable dt = DBHelper.GetDataTable(sql, 1);
//手动添加列 要在指定数据源之前
dgvUserNew.AutoGenerateColumns = false;
//指定数据源
dgvUserNew.DataSource = dt;
//没有事先手动添加列的情况
//dgvUserNew.AutoGenerateColumns = true;//指定数据源,是否自动创建列
//手动添加列 不让控件自动创建列
//更多的情况:dgvUserNew的列标题是中文名????
//1.可以对sql语句作文章--为列名取别名
//2.查询结果集可能包含更多列的数据,我只是调用,但仍然只显示这几个列???----手动添加好列
//一般情况下,根据需求,只查询需要的列--推荐的方式
}
private void AddColumnsAndRows()
{
//添加列
DataGridViewColumn col1 = new DataGridViewCheckBoxColumn();
col1.Name = "colChk";
col1.HeaderText = "选择";
dgvUserNew.Columns.Add(col1);
DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn();
col2.Name = "colId";
col2.HeaderText = "编号";
dgvUserNew.Columns.Add(col2);
DataGridViewTextBoxColumn col3 = new DataGridViewTextBoxColumn();
col3.Name = "colUserName";
col3.HeaderText = "姓名";
dgvUserNew.Columns.Add(col3);
DataGridViewLinkColumn col4 = new DataGridViewLinkColumn();
col4.Name = "colDel";
col4.HeaderText = "删除";
dgvUserNew.Columns.Add(col4);
//添加数据 行
DataGridViewRow dr = new DataGridViewRow();
DataGridViewCell cell1 = new DataGridViewCheckBoxCell();
cell1.Value = false;
DataGridViewCell cell2 = new DataGridViewTextBoxCell();
cell2.Value = 1;
DataGridViewCell cell3 = new DataGridViewTextBoxCell();
cell3.Value = "admin";
DataGridViewCell cell4 = new DataGridViewLinkCell();
cell4.Value = "删除";
dr.Cells.Add(cell1);
dr.Cells.Add(cell2);
dr.Cells.Add(cell3);
dr.Cells.Add(cell4);
dgvUserNew.Rows.Add(dr);
}
private void dgvUsers_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
//MessageBox.Show(e.RowIndex.ToString());
}
//即时触发CellValueChanged事件
private void dgvUsers_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
//当前单元格是否有未提交的更改
if(dgvUsers.IsCurrentCellDirty)
{
dgvUsers.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
//点击单元格内容时发生
private void dgvUsers_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCell cell = dgvUsers.Rows[e.RowIndex].Cells[e.ColumnIndex];
if(cell.FormattedValue.ToString()=="删除")
{
MessageBox.Show("删除");
}
else if(cell.FormattedValue.ToString() == "修改")
{
MessageBox.Show("修改");
}
}
}
DataGridView绑定List
DataGridView绑定List<T>列表
绑定的数据源:DataTable--- DataGridView行填充的数据对象----DataRowView.Row---DataRow
List列表--- 实体 UserInfoNew
DataGridView.Rows[0].DataBoundItem object
操作DataGridView的数据源的方式
2种:
1.DataTable ---List列表 :行--对象 多行---List集合 数据量大
2.SqlDataReader --- 读取过程中,一条数据---实体对象----List集合 数据量不大
public partial class FrmDataGridView : Form
{
public FrmDataGridView()
{
InitializeComponent();
}
private void FrmDataGridView_Load(object sender, EventArgs e)
{
//绑定List列表并显示
string sql = "select UserId,UserName,Age from UserInfos";
SqlDataReader dr = DBHelper.ExecuteReader(sql, 1);
List<UserInfoNew> list = new List<UserInfoNew>();
if(dr!=null)
{
while(dr.Read())//即时存储
{
UserInfoNew user = new UserInfoNew();
user.UserId = int.Parse(dr["UserId"].ToString());
user.UserName = dr["UserName"].ToString();
user.Age= int.Parse(dr["Age"].ToString());
list.Add(user);
}
dr.Close();//关闭
}
dgvUserNew.AutoGenerateColumns = false;//不自动创建列
dgvUserNew.DataSource = list;//指定数据源
}
private void BindDataTable()
{
// string sql = "select UserId,UserName,Age from UserInfos";
//string sql = "select UserId 编号,UserName 姓名,Age 年龄 from UserInfos";
string sql = "select * from UserInfos";
//获取数据
DataTable dt = DBHelper.GetDataTable(sql, 1);
//手动添加列 要在指定数据源之前
//dgvUserNew.AutoGenerateColumns = false;
//指定数据源
dgvUserNew.DataSource = dt;
//没有事先手动添加列的情况
//dgvUserNew.AutoGenerateColumns = true;//指定数据源,是否自动创建列
//手动添加列 不让控件自动创建列
//更多的情况:dgvUserNew的列标题是中文名????
//1.可以对sql语句作文章--为列名取别名
//2.查询结果集可能包含更多列的数据,我只是调用,但仍然只显示这几个列???----手动添加好列
//一般情况下,根据需求,只查询需要的列--推荐的方式
}
private void AddColumnsAndRows()
{
//添加列
DataGridViewColumn col1 = new DataGridViewCheckBoxColumn();
col1.Name = "colChk";
col1.HeaderText = "选择";
dgvUserNew.Columns.Add(col1);
DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn();
col2.Name = "colId";
col2.HeaderText = "编号";
dgvUserNew.Columns.Add(col2);
DataGridViewTextBoxColumn col3 = new DataGridViewTextBoxColumn();
col3.Name = "colUserName";
col3.HeaderText = "姓名";
dgvUserNew.Columns.Add(col3);
DataGridViewLinkColumn col4 = new DataGridViewLinkColumn();
col4.Name = "colDel";
col4.HeaderText = "删除";
dgvUserNew.Columns.Add(col4);
//添加数据 行
DataGridViewRow dr = new DataGridViewRow();
DataGridViewCell cell1 = new DataGridViewCheckBoxCell();
cell1.Value = false;
DataGridViewCell cell2 = new DataGridViewTextBoxCell();
cell2.Value = 1;
DataGridViewCell cell3 = new DataGridViewTextBoxCell();
cell3.Value = "admin";
DataGridViewCell cell4 = new DataGridViewLinkCell();
cell4.Value = "删除";
dr.Cells.Add(cell1);
dr.Cells.Add(cell2);
dr.Cells.Add(cell3);
dr.Cells.Add(cell4);
dgvUserNew.Rows.Add(dr);
}
private void dgvUsers_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
//MessageBox.Show(e.RowIndex.ToString());
}
//即时触发CellValueChanged事件
private void dgvUsers_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
//当前单元格是否有未提交的更改
if(dgvUsers.IsCurrentCellDirty)
{
dgvUsers.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
//点击单元格内容时发生
private void dgvUsers_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCell cell = dgvUsers.Rows[e.RowIndex].Cells[e.ColumnIndex];
if(cell.FormattedValue.ToString()=="删除")
{
MessageBox.Show("删除");
}
else if(cell.FormattedValue.ToString() == "修改")
{
MessageBox.Show("修改");
}
}
private void button1_Click(object sender, EventArgs e)
{
//获取数据源
List<UserInfoNew> list = dgvUserNew.DataSource as List<UserInfoNew>;
//如果要对数据进行修改
//1.获取数据源
//2.断开DataGridView与数据源关系
dgvUserNew.DataSource = null;
//3.操作数据源
list.RemoveAt(0);
list[1].UserName = "小明";
//4.重新指定数据源
dgvUserNew.DataSource = list;
//行对象获取方式
// UserInfoNew user = dgvUserNew.Rows[0].DataBoundItem as UserInfoNew;
//DataTable
// DataRow dr = (dgvUserNew.Rows[0].DataBoundItem as DataRowView).Row;
}
}
ComboBox列的使用
- DataGridView控件ComboBox列的使用
- 下拉框---多个选择的项-----初始化---从数据库里加载部门信息表,数据绑定到ComboBox中
- 就是一个绑定ComboBox控件一样的方式
- CheckBox列的使用 ---批量操作数据,---选择数据
- 全选、反选
public partial class FrmComboBox : Form
{
public FrmComboBox()
{
InitializeComponent();
}
private void FrmComboBox_Load(object sender, EventArgs e)
{
//单项的添加
cboList.Items.Clear();//清除
//cboList.Items.Add(123);
//cboList.Items.Add("admin");
//cboList.Items.Add(23.45);
//cboList.Items.AddRange(new string[] { "adddd", "bcdd" });
可以随意修改项
//cboList.Items.Remove("admin");
//cboList.Items.RemoveAt(1);
List<UserInfo> list = new List<UserInfo>();
//添加项数量很大的情况,出现闪烁
//cboList.BeginUpdate();
添加操作
//foreach (var item in list)
//{
// cboList.Items.Add(item);
//}
//cboList.DisplayMember = "Name";
//cboList.ValueMember = "Id";
//cboList.EndUpdate();
list.Add(new UserInfo()
{
Id = 1,
Name = "admin"
});
list.Add(new UserInfo()
{
Id = 2,
Name = "lycchun"
});
list.Add(new UserInfo()
{
Id = 3,
Name = "lwb"
});
list.Add(new UserInfo()
{
Id = 4,
Name = "Eleven"
});
list.Add(new UserInfo()
{
Id = 5,
Name = "Jason"
});
cboList.DataSource = list;
cboList.DisplayMember = "Name";
cboList.ValueMember = "Id";
//ListBox一样,问题:指定了DataSource,就不能直接修改项的集合
//同样,把项集合的修改转换成对数据源的修改上
//数据项不多的情况,又要修改项集合,用Items.Add添加项
//ComboBox经常使用:做选择使用,一般不修改项集合
}
//选择项更改时发生 一个下拉框,一般不会注册这个事件
//级联下拉框 会使用这个事件
private void cboList_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show((cboList.SelectedItem as UserInfo).Name);
}
}
Adapter提交GridView的数据
DataGridView是新增、修改、删除数据,数据源是DataTable,
利用SqlDataAdapter的Update()提交到数据库。
原理:DataRow ---RowState :Added Modified Deleted UnChanged Detached
Insert Update Delete
将DataTable里所做的Insert Update Delete 提交到数据库 --一致
实例操作--所做修改是否更新到了数据库里???---SqlCommandBuilder对象--可以将DataGridView所做的修改(DataTable)提交到数据库---小小bug? 时间设置了默认值 ,但是没进去
---通过手动配置Insert Update Delete命令,可以避免这个bug
总结:利用SqlDataAdapter的Update()提交到数据库。--提交的过程:配置命令的过程
TreeView介绍
TreeView控件 树形控件 分层显示标签的项 集合
介绍
属性
方法
- BeginUpdate() 禁止重绘
- EndUpdate() 启用重绘
- CollapseAll 折叠所有节点
- ExpandAll 展开所有
- GetNodeAt() 获取节点
事件
- AfterCheck ---Before
- AfterSelect---Before
- AfterCollapse---Before
- AfterExpand---Before
- NodeMouseClick
TreeView代码添加节点
1.节点介绍 TreeNode Name --唯一标识节点 Text 显示的文本 Nodes 子节点集合
2,代码添加节点
应用:权限分配
public partial class FrmTreeView : Form
{
public FrmTreeView()
{
InitializeComponent();
}
private void FrmTreeView_Load(object sender, EventArgs e)
{
treeView1.Nodes.Clear();//清除所有节点
//如果一个节点下面有子节点,我是应该先把这个节点添加到treeview中,还是先应该添加好子节点,再添加到treeview?
//都可以
//添加节点过程:创建一个节点,将这个节点添加到treeview的Nodes集合;创建一个节点,将这个节点添加到当前节点的Nodes集合。。。。。。
//代码添加节点---手动添加的过程用代码翻译出来而已。
//更多的应用不是这样,而采用递归的方式,加载节点及子节点,数据的来源:制作成张表,ParentId---父节点编号
//创建节点
TreeNode root = new TreeNode();
root.Name = "root"; //节点名称
root.Text = "学生管理系统";//节点文本
treeView1.Nodes.Add(root);//将一个节点添加 到TreeView上
TreeNode subNode = new TreeNode();
subNode.Name = "stuManage";
subNode.Text = "学生管理";
root.Nodes.Add(subNode);//添加一个子节点
TreeNode thirdNode = new TreeNode();
thirdNode.Name = "addStudent";
thirdNode.Text = "新增学生";
subNode.Nodes.Add(thirdNode);
thirdNode = new TreeNode();
thirdNode.Name = "stuList";
thirdNode.Text = "学生列表";
subNode.Nodes.Add(thirdNode);
subNode = new TreeNode();
subNode.Name = "classManage";
subNode.Text = "班级管理";
root.Nodes.Add(subNode);//添加一个子节点
subNode = new TreeNode();
subNode.Name = "gradeManage";
subNode.Text = "年级管理";
root.Nodes.Add(subNode);//添加一个子节点
}
}
递归加载TreeView节点及子节点
- 动态加载菜单表(递归)
- 表数据:存储的是节点与子节点关系数据 看不出层次关系
- 动态加载数据到TreeView控件的流程
- 1.表数据获取出来
- 2.创建一个方法:创建节点并且添加到TreeView 递归的原理:自己调用自己
- (子节点可以有多个)
- 3.调用方法 创建节点 体现在TreeView中 --有层次关系的数据
- 动态加载节点:节点创建好添加到TreeView中,再创建它的子节点,再添加到它的Nodes集合中
public partial class FrmTreeView : Form
{
public FrmTreeView()
{
InitializeComponent();
}
private void FrmTreeView_Load(object sender, EventArgs e)
{
treeView1.Nodes.Clear();//清除所有节点
//1. 获取数据
DataTable dtMenus = DBHelper.GetDataTable("select Id,MName,ParentId from MenuInfos", 1);
//3.调用方法,添加节点
CreateNode(dtMenus, null, 0);
}
//2.添加节点(递归)
private void CreateNode(DataTable dt,TreeNode pNode,int parentId)
{
//1.获取要创建的节点数据
DataRow[] rows = dt.Select("ParentId=" + parentId);
if(rows.Length>0)
{
foreach (DataRow r in rows)
{
//2.
TreeNode node = new TreeNode();
node.Name = r["Id"].ToString();
node.Text = r["MName"].ToString();
//3.直接添加到TreeView Nodes 还是添加指定节点的Nodes里?
if (pNode != null)
pNode.Nodes.Add(node);
else
treeView1.Nodes.Add(node);
//4.判断当前节点下有没有子节点
CreateNode(dt, node, int.Parse(node.Name));
}
}
}
//代码手动添加节点
private void InitNodes()
{
//如果一个节点下面有子节点,我是应该先把这个节点添加到treeview中,还是先应该添加好子节点,再添加到treeview?
//都可以
//添加节点过程:创建一个节点,将这个节点添加到treeview的Nodes集合;创建一个节点,将这个节点添加到当前节点的Nodes集合。。。。。。
//代码添加节点---手动添加的过程用代码翻译出来而已。
//更多的应用不是这样,而采用递归的方式,加载节点及子节点,数据的来源:制作成张表,ParentId---父节点编号
//创建节点
TreeNode root = new TreeNode();
root.Name = "root"; //节点名称
root.Text = "学生管理系统";//节点文本
treeView1.Nodes.Add(root);//将一个节点添加 到TreeView上
TreeNode subNode = new TreeNode();
subNode.Name = "stuManage";
subNode.Text = "学生管理";
root.Nodes.Add(subNode);//添加一个子节点
TreeNode thirdNode = new TreeNode();
thirdNode.Name = "addStudent";
thirdNode.Text = "新增学生";
subNode.Nodes.Add(thirdNode);
thirdNode = new TreeNode();
thirdNode.Name = "stuList";
thirdNode.Text = "学生列表";
subNode.Nodes.Add(thirdNode);
subNode = new TreeNode();
subNode.Name = "classManage";
subNode.Text = "班级管理";
root.Nodes.Add(subNode);//添加一个子节点
subNode = new TreeNode();
subNode.Name = "gradeManage";
subNode.Text = "年级管理";
root.Nodes.Add(subNode);//添加一个子节点
}
}
TreeView父子节点的勾选处理
TreeView节点的勾选处理
1.父节点勾选或取消,它的所有子节点与它一致
2.只要有一个子节点勾选,父节点就勾选
子节点全部不勾选,父节点就不勾选
public partial class FrmTreeView : Form
{
public FrmTreeView()
{
InitializeComponent();
}
private void FrmTreeView_Load(object sender, EventArgs e)
{
treeView1.Nodes.Clear();//清除所有节点
//1. 获取数据
DataTable dtMenus = DBHelper.GetDataTable("select Id,MName,ParentId from MenuInfos", 1);
//3.调用方法,添加节点
CreateNode(dtMenus, null, 0);
}
//2.添加节点(递归)
private void CreateNode(DataTable dt,TreeNode pNode,int parentId)
{
//1.获取要创建的节点数据
DataRow[] rows = dt.Select("ParentId=" + parentId);
if(rows.Length>0)
{
foreach (DataRow r in rows)
{
//2.
TreeNode node = new TreeNode();
node.Name = r["Id"].ToString();
node.Text = r["MName"].ToString();
//3.直接添加到TreeView Nodes 还是添加指定节点的Nodes里?
if (pNode != null)
pNode.Nodes.Add(node);
else
treeView1.Nodes.Add(node);
//4.判断当前节点下有没有子节点
CreateNode(dt, node, int.Parse(node.Name));
}
}
}
//代码手动添加节点
private void InitNodes()
{
//如果一个节点下面有子节点,我是应该先把这个节点添加到treeview中,还是先应该添加好子节点,再添加到treeview?
//都可以
//添加节点过程:创建一个节点,将这个节点添加到treeview的Nodes集合;创建一个节点,将这个节点添加到当前节点的Nodes集合。。。。。。
//代码添加节点---手动添加的过程用代码翻译出来而已。
//更多的应用不是这样,而采用递归的方式,加载节点及子节点,数据的来源:制作成张表,ParentId---父节点编号
//创建节点
TreeNode root = new TreeNode();
root.Name = "root"; //节点名称
root.Text = "学生管理系统";//节点文本
treeView1.Nodes.Add(root);//将一个节点添加 到TreeView上
TreeNode subNode = new TreeNode();
subNode.Name = "stuManage";
subNode.Text = "学生管理";
root.Nodes.Add(subNode);//添加一个子节点
TreeNode thirdNode = new TreeNode();
thirdNode.Name = "addStudent";
thirdNode.Text = "新增学生";
subNode.Nodes.Add(thirdNode);
thirdNode = new TreeNode();
thirdNode.Name = "stuList";
thirdNode.Text = "学生列表";
subNode.Nodes.Add(thirdNode);
subNode = new TreeNode();
subNode.Name = "classManage";
subNode.Text = "班级管理";
root.Nodes.Add(subNode);//添加一个子节点
subNode = new TreeNode();
subNode.Name = "gradeManage";
subNode.Text = "年级管理";
root.Nodes.Add(subNode);//添加一个子节点
}
bool isMouseClick = true;
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
isMouseClick = false;
//子节点勾选
SetChildNodesState(e.Node);
//父节点勾选
SetParentNodeState(e.Node);
isMouseClick = true;
}
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
if (isMouseClick)
{
treeView1.SelectedNode = e.Node; //当前操作节点选中
}
}
//递归处理子节点的勾选
private void SetChildNodesState(TreeNode node)
{
if (node.Nodes.Count > 0)
{
foreach (TreeNode n in node.Nodes)
{
n.Checked = node.Checked;
SetChildNodesState(n);
}
}
}
private void SetParentNodeState(TreeNode node)
{
TreeNode pNode = node.Parent;//获取父节点
if(pNode!=null)
{
bool bl = false;
foreach (TreeNode n in pNode.Nodes)
{
if (n.Checked)
{
bl = true;
break;
}
}
pNode.Checked = bl;
SetParentNodeState(pNode);
}
}
}
自定义控件之复合控件
用户控件开发
1.分类 组合控件 在原有控件基础上,根据需要进行组合而形成一个新的控件 UserControl
扩展控件 在现在基础上,对它进行扩展:继承自原有控件,添加或扩展原有控件的性能
自定义控件 派生Control类,绘制全部由用户定义
2.组合控件
可视化外观
添加新的属性 应用窗体上,修改属性值,就可以即时看到变化
定义自定义的事件
Load 事件 应用窗体:Load事件 ----加载顺序:应用窗体:Load事件---- 用户控件 Load 事件
public partial class UserButton : UserControl
{
public UserButton()
{
InitializeComponent();
}
private string _lblText;
//Label的文本
public string LblText
{
get { return _lblText; }
set
{
_lblText = value;
lblContent.Text = _lblText;
}
}
private string _btnText;
//Button的文本
public string BtnText
{
get { return _btnText; }
set
{
_btnText = value;
btnConfirm.Text = _btnText;
}
}
//事件 调用:只能在自己内部调用
public event Action<object, EventArgs> ShowMsg;
private void UserButton_Load(object sender, EventArgs e)
{
//lblContent.Text = LblText;
//btnConfirm.Text = BtnText;
}
private void btnConfirm_Click(object sender, EventArgs e)
{
if (ShowMsg != null)
ShowMsg(sender, e);
}
}
自定义控件之扩展控件
用户控件--- 扩展控件
继承自原有控件提供 的类
public class ButtonEx:Button
{
private string _btnText;
//Button的文本
public string BtnText
{
get { return _btnText; }
set
{
_btnText = value;
Text = _btnText;
}
}
protected override void OnClick(EventArgs e)
{
this.ForeColor = Color.Red;
base.OnClick(e);
}
}