丰富“WinForms” 的一个别样"项目"(学生管理)

Posted 维尼熊的进阶路

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了丰富“WinForms” 的一个别样"项目"(学生管理)相关的知识,希望对你有一定的参考价值。

    一个别样的WinForms项目,他并没多么的新颖,但是它的用处确实有点多,或许会有你需要的地方;如果你对WinForms中那么多控件无法把握,又或者是你根本就不懂,那我觉得你应该好好看看,如果一个人的人生命运无法去选择时,那我觉得接受它将是冲刺命运终点的最好动力,一切的不公平都是你为了躲避困难而找的借口,年轻人就需要不平坦的人生道路,通过刻苦奋斗得来的果实永远是最甜、平坦的人生亦是最幸福的瞬间。

     那首先就是项目的框架分别是:登录(FrmLogin )——>主界面(FrmMain)——>修改密码(FrmUpdate)——>添加/修改/删除学生基本信息等。

    框架搭好之后,我们了解一些框架内的代码吧!至于具体的一些控件呢!只能是自己慢慢去看看,有些注意点大家可以记下,在控件生成后要及时去修改控件的“Name”的属性,如果够专业就尽量取专业点名字,那样对你可能会有帮助的。

    当界面形成后,事件会是你填写代码的最大障碍,所以WinForms的几个事件需要认真记住:(单击)Click,当界面显示在眼前就形成的(Load),窗体正在运行的(FormClosing),(鼠标在界面移动)mouseClick

    1.登录界面(FrmLogin)

点击登陆进去的代码:

复制代码
   string str = "Data source=.;Initial catalog=Myschool;Uid=sa";
            SqlConnection con = new SqlConnection(str);
            string sql = "select count(1) from student where studentname=\'"+txtUserName.Text+"\' and Loginpwd=\'"+txtPwd.Text+"\'";
            SqlCommand cmd = new SqlCommand(sql,con);
            try
            {
                con.Open();
                int count=Convert.ToInt32(cmd.ExecuteScalar());
                if (count>0)
                {
                 //隐藏原界面
                    this.Hide();
                //跳转至主界面
                    FormMain frm = new FormMain();
                    Tool.pwd = txtPwd.Text;
                    frm.Show();
                }
               
            }
            catch (Exception)
            {

                MessageBox.Show("出现异常");
            }
            finally 
            {
                con.Close();
            }
复制代码

2.跳转主界面(FrmMain)

菜单控件,工具控件、右键(contextMenuStrip)控件,ListView控件、视图等

其中有ListView五大视图:

  1.大图标(LargeIcon)

  2.小图标(SmallIcon)

  3.列表(List)

  4.详细信息(Detail)

  5.平铺(Tile)

 生成上方主界面ListView代码:

复制代码
 private void btnBig_Click(object sender, EventArgs e)
        {
            //设置listview的属性view为大图标
            lvlist.View = View.LargeIcon;
        }

        private void btnSmall_Click(object sender, EventArgs e)
        {
            //设置listview的属性view为小图标
            lvlist.View = View.SmallIcon;
        }

        private void btnTile_Click(object sender, EventArgs e)
        {
            //设置listview的属性view为平铺
            lvlist.View = View.Tile;
        }

        private void btnList_Click(object sender, EventArgs e)
        {
            //设置listview的属性view为列表
            lvlist.View = View.List;

        }

        private void btnDetails_Click(object sender, EventArgs e)
        {
            //设置listview的属性view为详细信息
            lvlist.View = View.Details;
        }
复制代码

跳转至其它的各个功能的窗体:

复制代码
        private void TsmiUpdate_Click(object sender, EventArgs e)
        {
            //修改密码
            FrmUpdate frm = new FrmUpdate();
            frm.Show();
        }

        private void lvlist_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void StuName_Click(object sender, EventArgs e)
        {
            //查找
            this.Hide();
            FrmColor frm = new FrmColor();
            frm.Show();
        }
复制代码

3.修改密码(FrmUpdate)

判断密码是否为空,修改密码是否成功

复制代码
 private void btnupdate_Click(object sender, EventArgs e)
        {
             string name = string.Empty;
            if (txtoldpwd.Text==name)
            {
               DialogResult result=MessageBox.Show("原密码为空","通知",MessageBoxButtons.YesNo,MessageBoxIcon.Information);
               if (result==DialogResult.No)
               {
                   this.Close();
               }
            }
             if (txtnewpwd.Text == name)
            {
                DialogResult result = MessageBox.Show("新密码密码为空", "通知", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (result == DialogResult.No)
                {
                    this.Close();
                }
            }
             if(txtOK.Text == name)
            {
                DialogResult result = MessageBox.Show("确认密码为空", "通知", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (result == DialogResult.No)
                {
                    this.Close();
                }
            }
             if (txtoldpwd.Text != name && txtnewpwd.Text != name && txtOK.Text != name)
             {
                 string str = "Data source=.;Initial catalog=Myschool;Uid=sa";
                 SqlConnection conn = new SqlConnection(str);
                 string sql = "update student set Loginpwd=\'" + txtnewpwd.Text + "\' where Loginpwd=\'" + txtoldpwd.Text + "\'";
                 SqlCommand cmd = new SqlCommand(sql, conn);
                 try
                 {
                     conn.Open();
                     if (txtOK.Text.Equals(txtnewpwd.Text))
                     {
                         int count = cmd.ExecuteNonQuery();
                         if (count > 0)
                         {
                             MessageBox.Show("修改成功");
                         }
                     }                                    
                 }
                 catch (Exception)
                 {

                     MessageBox.Show("异常!"); ;
                 }
                 finally
                 {
                     conn.Close();
                 }
             }
        }
        private void FrmUpdate_Load(object sender, EventArgs e)
        {
            txtoldpwd.Text = Tool.pwd;
        }
       private void btncancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
复制代码

4.查找学生信息(FrmReseach)

从查找可以跳转到添加/修改/删除窗体

复制代码
  private void btnselect_Click(object sender, EventArgs e)
        {
            UpdateSelect();
        }
        //按学生编号查找的方法
        public void LoadDataFromDBToListView(string sql)
        {
            string str = "data source=.;initial catalog=MySchool;uid=sa";
            SqlConnection con = new SqlConnection(str);

            SqlCommand cmd = new SqlCommand(sql, con);
            try
            {
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr != null)
                {
                    if (dr.HasRows)
                    {
                        while (dr.Read())
                        {
                            //每从DB中读取出一条数据,需要形成一个ListViewItem对象,代表的是ListView中的一行
                            int stuNo = Convert.ToInt32(dr["studentno"]);
                            //第二列 学生名字
                            string stuName = Convert.ToString(dr["studentname"]);
                            //第三列  性别
                            string stugender = Convert.ToString(dr["gender"]);
                            //第四列  年级名称
                            string gname = Convert.ToString(dr["gradename"]);
                            //第五列  电话
                            string phone = Convert.ToString(dr["phone"]);
                            //第六列   地址
                            string address = Convert.ToString(dr["address"]);
                            //第七列   邮箱
                            string email = Convert.ToString(dr["email"]);
                            //第八列   出生日期
                            string birthday = Convert.ToString(dr["birthday"]);
                            ListViewItem lvItem = new ListViewItem(stuNo.ToString());
                            lvItem.SubItems.Add(stuName);
                            lvItem.SubItems.Add(stugender);
                            lvItem.SubItems.Add(gname);
                            lvItem.SubItems.Add(phone);
                            lvItem.SubItems.Add(address);
                            lvItem.SubItems.Add(email);
                            lvItem.SubItems.Add(birthday);
                            //让lvItem和ListView关联
                           lvlist.Items.Add(lvItem);
                           lvlist.FullRowSelect = true;
                           lvlist.ContextMenuStrip = ctmslist;
                        }
                        dr.Close();
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("异常!"); ;
            }
            finally
            {
                con.Close();
            }
        }
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sql = @"select Studentno,Studentname,Gender,gradename
                          ,phone,address,email,birthday from student,grade
                            where student.gradeid=grade.gradeid";
            LoadDataFromDBToListView(sql);
        }
        public void UpdateSelect()
        {
            lvlist.Items.Clear();
            string sql = @"select Studentno,Studentname,Gender,gradename,phone,address
                            ,email,birthday from student,grade
                            where student.gradeid=grade.gradeid and studentname like \'%" + txtname.Text + "%\' ";
            LoadDataFromDBToListView(sql);
        }
        private void TsStudentInfo_Click(object sender, EventArgs e)
        {
            int stuno=Convert.ToInt32(lvlist.SelectedItems[0].Text);
            FrmEditStu frm = new FrmEditStu();
            frm.stuno = stuno;
            frm.frmselect = this;
            frm.Show();
        }

        private void FrmColor_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void 删除学生信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int sno = Convert.ToInt32(lvlist.SelectedItems[0].Text);
            FrmEditStu frm = new FrmEditStu();
            frm.stuno = sno;
            frm.frmselect = this;
            frm.Show();
        }
复制代码

5.添加学生信息(FrmEditStu)

修改学生信息:

 

删除学生信息:

 

 

添加到数据库:

复制代码
  private void btnSave_Click(object sender, EventArgs e)
        {
            //接收到的学号
            //判断学号是否为空来选择sql语句
            //判断是否要删除信息
            if (sno!=0)
            {
                DialogResult result=MessageBox.Show("是否删除?","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Error);
                if (result==DialogResult.Yes)
                {
                    //删除
                    this.Hide();
                    ChangDelete();
                }
            }
                if (stuno!=0)
                {
                    //修改
                    this.Hide();
                    GetUpdate();
                }            
                else
                {
                    //新增
                    this.Hide();
                     GetSave();
                }                  
          }          
            //判断stuno是否有值来修改select语句
            //新增
             public void GetSave()
        {
            string pwd = txtpwd.Text;//密码
            string pwdTrue = txtPwdTrue.Text;//确认密码
            string name = txtStuName.Text;//学生名
            string stuGender = string.Empty;//取单选列表
            if (rbtnGenderTure.Checked)
            {
                stuGender = "1";
            }
            else
            {
                stuGender = "0";
            }
            //给下拉框取值
            int gid = GetIdByName();
            string phone = txtPhone.Text;//电话
            string address = txtAddress.Text;//地址
            DateTime dt = dtBirthday.Value;//日期
            string stuEmail = txtEmail.Text;//邮箱
            //StudentNo, LoginPwd, StudentName, Gender, GradeId, Phone, Address, Birthday, Email
            string sql = "insert into student values(\'" + pwd + "\',\'" + name + "\',\'" + stuGender + "\'," + gid + ",\'" + phone + "\',\'" + address + "\',\'" + dt + "\',\'" + stuEmail + "\')";
            string str = "Data source=.;initial catalog=MySchool;uid=sa";
            SqlConnection con = new SqlConnection(str);
            SqlCommand cmd = new SqlCommand(sql, con);
            con.Open();
            if (pwd.Equals(pwdTrue))
            {
                int count = cmd.ExecuteNonQuery();
                if (count > 0)
                {
                    frmselect.UpdateSelect();
                    MessageBox.Show("成功!");
                }
                con.Close();
            }
            else
            {
                MessageBox.Show("前后密码不匹配");
            }       
        }
            //修改
             public void GetUpdate()
             {               
                 string name = txtStuName.Text;//学生名
                 string stuGender = string.Empty;//取单选列表
                 if (rbtnGenderTure.Checked)
                 {
                     stuGender = "1";
                 }
                 else
                 {
                     stuGender = "0";
                 }
                 //给下拉框取值
                 int gid = GetIdByName();
                 string phone = txtPhone.Text;//电话
                 string address = txtAddress.Text;//地址
                 DateTime dt = dtBirthday.Value;//日期
                 string stuEmail = txtEmail.Text;//邮箱
                 //StudentNo, LoginPwd, StudentName, Gender, GradeId, Phone, Address, Birthday, Email
                 string sql = @"update student set studentname=\'" + name +
                     "\',gender=\'" + stuGender + "\',gradeid=\'" + gid + "\',phone=\'" +
                     phone + "\',address=\'"+address+"\',birthday=\'"+dt+"\',email=\'"+stuEmail+
                       "\' where studentno="+txtStuNo.Text+"";        
                 string str = "Data source=.;initial catalog=MySchool;uid=sa";
                 SqlConnection con = new SqlConnection(str);
                 SqlCommand cmd = new SqlCommand(sql, con);
                     con.Open();                             
                     int count = cmd.ExecuteNonQuery();
                     con.Close();
                     if (count > 0)
                     {
                         frmselect.UpdateSelect();
                         MessageBox.Show("成功!");
                     }                                             
             }
            //删除
             public void ChangDelete()
             {
                 string pwd = txtpwd.Text;//密码
                 string pwdTrue = txtPwdTrue.Text;//确认密码
                 string name = txtStuName.Text;//学生名
                 string stuGender = string.Empty;//取单选列表
                 if (rbtnGenderTure.Checked)
                 {
                     stuGender = "1";
                 }
                 else
                 {
                     stuGender = "0";
                 }
                 //给下拉框取值
                 int gid = GetIdByName();
                 string phone = txtPhone.Text;//电话
                 string address = txtAddress.Text;//地址
                 DateTime dt = dtBirthday.Value;//日期
                 string stuEmail = txtEmail.Text;//邮箱
                 //StudentNo, LoginPwd, StudentName, Gender, GradeId, Phone, Address, Birthday, Email
                 string sql = @"delete from student where studentno=\'"+txtStuNo.Text+"\' ";
                 string str = "Data source=.;initial catalog=MySchool;uid=sa";
                 SqlConnection con = new SqlConnection(str);
                 SqlCommand cmd = new SqlCommand(sql, con);
                 con.Open();
                 if (pwd.Equals(pwdTrue))
                 {
                     int count = cmd.ExecuteNonQuery();
                     if (count > 0)
                     {
                         frmselect.UpdateSelect();
                         MessageBox.Show("成功!");
                     }
                 }
                 else
                 {
                     MessageBox.Show("前后密码不匹配");
                 }
                 con.Close();
             }
            //根据对应条件查询班级id
             public int GetIdByName()
        {
             string str = "Data source=.;initial catalog=MySchool;uid=sa";
             SqlConnection con = new SqlConnection(str);
             string sql = "select gradeid from grade where gradename=\'"+cmbGrade.Text+"\'";
             SqlCommand cmd = new SqlCommand(sql, con);
             int gid = 0;
             try
             {
                con.Open();
                gid =Convert.ToInt32(cmd.ExecuteScalar());
             }
             catch (Exception)
             {

                MessageBox.Show("网络异常");
             }
             finally
             {
                con.Close();
             }
              return gid;
        }
            //根据对应条件查询班级gname
             public string GetNameById(int gid)
             {
                 string str = "Data source=.;initial catalog=MySchool;uid=sa";
                 SqlConnection con = new SqlConnection(str);
                 string sql = "select gradename from grade where gradeid=" + gid + "";
                 SqlCommand cmd = new SqlCommand(sql, con);
                 string name = "";
                 try
                 {
                     con.Open();
                     name =cmd.ExecuteScalar().ToString();
                 }
                 catch (Exception)
                 {

                     MessageBox.Show("网络异常");
                 }
                 finally
                 {
                     con.Close();
                 }
                 return name;
             }
             //加载年级下拉框
             public void LoadGrade()
             {
                 //拿到所有年级名称
                 string str = "Data source=.;Initial catalog=MySchool;uid=sa";
                 SqlConnection con = new SqlConnection(str);
                 string sql = "select gradename from grade";
                 SqlCommand cmd = new SqlCommand(sql, con);
                 try
                 {
                     con.Open();
                     SqlDataReader dr = cmd.ExecuteReader();
                     if (dr != null)
                     {
                         if (dr.HasRows)
                         {
                             while (dr.Read())
                             {
                                 string gname = dr["gradename"].ToString();
                                 //每读到一个年级名称,我就将"S1",添加到下拉框
                                 cmbGrade.Items.Add(gname);
                             }
                         }
                     }
                 }
                 catch (Exception ex)
                 {
                     MessageBox.Show("网络异常");
                 }
                 finally
                 {
                     con.Close();
                 }
             }
             //根据学号加载其他信息
             public void LoadStuInfoByStuNo()
             {
                 string str = "Data source=.;Initial catalog=MySchool;uid=sa";
                 SqlConnection con = new SqlConnection(str);
                 string sql = "select * from student where studentno="+stuno+"";
                 SqlCommand cmd = new SqlCommand(sql, con);
                 try
                 {
                     con.Open();
                     SqlDataReader dr = cmd.ExecuteReader();
                     txtStuNo.Text = stuno.ToString();
                     if (dr!=null)
                     {
                         if (dr.HasRows)
                         {
                             while (dr.Read())
                             {
                                 string stuname = dr["studentname"].ToString();
                                 txtStuName.Text = stuname;//姓名
                                 string stuGender = dr["gender"].ToString();
                                 if (stuGender == "1")
                                 {
                                     rbtnGenderTure.Checked = true;
                                 }
                                 else if (stuGender == "0")
                                 {
                                     rbtnGender.Checked = true;
                                 }//性别
                                 int gid = Convert.ToInt32(dr["gradeid"]);
                                 string gname = GetNameById(gid);
                                 cmbGrade.Text = gname;//年级
                                 string stuphone = dr["phone"].ToString();
                                 txtPhone.Text = stuphone;//电话
                                 string stuaddress = dr["address"].ToString();
                                 txtAddress.Text = stuaddress;//地址
                                 string stuemail = dr["email"].ToString();
                                 txtEmail.Text = stuemail;//邮箱
                                 DateTime stubirthday = Convert.ToDateTime(dr["birthday"]);
                                 dtBirthday.Value = stubirthday;//出生日期    
                             }
                         }
                     }
                 }
                 catch (Exception)
                 {
                     MessageBox.Show("异常!!"); ;
                 }
                 finally 
                 {
                 
                 }
             }
            
        private void FrmEditStu_Load(object sender, EventArgs e)
        {   
            //判断学号是否为空来选择sql语句
            if ( sno != 0)
            {
                DialogResult result = MessageBox.Show("是否删除?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (result == DialogResult.Yes)
                {
                    this.Text = "删除学生信息";
                    btnSave.Text = "删除";
                    LoadStuInfoByStuNo();
                }
            }
                if(stuno!=0)
                {
                    this.Text = "修改学生信息";
                    btnSave.Text = "修改";
                    LoadStuInfoByStuNo();
                }           
            else
            {
                btnSave.Text = "保存";
                LoadGrade();
            }
        }
        private void FrmEditStu_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            this.Close();
        }
复制代码

6.动态图片时钟

计时控件:

通过时间来让几张图连接形成动态的计时:

复制代码
  private int index = 0;
        private void timers_Tick(object sender, EventArgs e)
        {
            if (index<imglist.Images.Count-1)
            {
                index++;
            }
            else
            {
                index = 0;
            }
            piclist.Image = imglist.Images[index];
        }
复制代码

      WinForms很重要,虽说难度不是很大,但它的内容太多,之间的融合又太复杂,所以难易与否只有自己知道,但只要认真听课、刻苦学习,我想时间会给我们大家最好的结果,所以我希望大家能指出我的一些不足之处,相信我们的互帮互助能让我们都变得更好。

以上是关于丰富“WinForms” 的一个别样"项目"(学生管理)的主要内容,如果未能解决你的问题,请参考以下文章

WinForms ListBox 控件上的多行列表项?

如何提供“退出”菜单项 [重复]

无法添加用户控件“无法加载工具箱项”C#winforms

如何把WinForms中DataGrid的第一列放上复选框,可以多项选择???急!

WinForms 中的 C# 虚拟列表视图

如何拦截所有键盘事件并防止在 WinForms 应用程序中失去焦点?