C#项目实战

2 篇文章 0 订阅
事件
public delegate void NumManipulationHandler(NumEventArgs e);
// 基于上面的委托定义事件
public event NumManipulationHandler ChangeNum;
 public class Program
    {
        public static void Main()
        {

            NumEvent even = new NumEvent(0);
            even.ChangeNum += EventAction.Action;

            even.SetValue(7);
            even.SetValue(11);

            System.Console.ReadKey();
        }
    }

    public class NumEvent
    {
        private int value;

        public delegate void NumManipulationHandler(NumEventArgs e);

        public event NumManipulationHandler ChangeNum;

        public virtual void OnChangeNum(NumEventArgs e)
        {
            ChangeNum?.Invoke(e);
        }

        public NumEvent(int n)
        {
            SetValue(n);
        }

        public void SetValue(int n)
        {
            if (value != n)
            {
                NumEventArgs e = new NumEventArgs(n);
                value = n;
                OnChangeNum(e);
            }
        }
    }

    public class EventAction
    {
        public static void Action(NumEventArgs e)
        {
            System.Console.WriteLine("value : " + e.value);
        }
    }

    public class NumEventArgs : EventArgs
    {
        public int value;
        public NumEventArgs(int _value)
        {
            this.value = _value;
        }
    }
ini读写 
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;

namespace DEMOBus
{
    public class IniFile
    {
        private string m_FileName;

        public string FileName
        {
            get { return m_FileName; }
            set { m_FileName = value; }
        }

        [DllImport("kernel32.dll")]
        private static extern int GetPrivateProfileInt(
            string lpAppName,
            string lpKeyName,
            int nDefault,
            string lpFileName
            );

        [DllImport("kernel32.dll")]
        private static extern int GetPrivateProfileString(
            string lpAppName,
            string lpKeyName,
            string lpDefault,
            StringBuilder lpReturnedString,
            int nSize,
            string lpFileName
            );

        [DllImport("kernel32.dll")]
        private static extern int WritePrivateProfileString(
            string lpAppName,
            string lpKeyName,
            string lpString,
            string lpFileName
            );

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="aFileName">Ini文件路径</param>
        public IniFile(string aFileName)
        {
            this.m_FileName = aFileName;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public IniFile()
        { }

        /// <summary>
        /// [扩展]读Int数值
        /// </summary>
        /// <param name="section">节</param>
        /// <param name="name">键</param>
        /// <param name="def">默认值</param>
        /// <returns></returns>
        public int ReadInt(string section, string name, int def)
        {
            return GetPrivateProfileInt(section, name, def, this.m_FileName);
        }

        /// <summary>
        /// [扩展]读取string字符串
        /// </summary>
        /// <param name="section">节</param>
        /// <param name="name">键</param>
        /// <param name="def">默认值</param>
        /// <returns></returns>
        public string ReadString(string section, string name, string def)
        {
            StringBuilder vRetSb = new StringBuilder(2048);
            GetPrivateProfileString(section, name, def, vRetSb, 2048, this.m_FileName);
            return vRetSb.ToString();
        }

        /// <summary>
        /// [扩展]写入Int数值,如果不存在 节-键,则会自动创建
        /// </summary>
        /// <param name="section">节</param>
        /// <param name="name">键</param>
        /// <param name="Ival">写入值</param>
        public void WriteInt(string section, string name, int Ival)
        {

            WritePrivateProfileString(section, name, Ival.ToString(), this.m_FileName);
        }

        /// <summary>
        /// [扩展]写入String字符串,如果不存在 节-键,则会自动创建
        /// </summary>
        /// <param name="section">节</param>
        /// <param name="name">键</param>
        /// <param name="strVal">写入值</param>
        public void WriteString(string section, string name, string strVal)
        {
            WritePrivateProfileString(section, name, strVal, this.m_FileName);
        }

        /// <summary>
        /// 删除指定的 节
        /// </summary>
        /// <param name="section"></param>
        public void DeleteSection(string section)
        {
            WritePrivateProfileString(section, null, null, this.m_FileName);
        }

        /// <summary>
        /// 删除全部 节
        /// </summary>
        public void DeleteAllSection()
        {
            WritePrivateProfileString(null, null, null, this.m_FileName);
        }

        /// <summary>
        /// 读取指定 节-键 的值
        /// </summary>
        /// <param name="section"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public string IniReadValue(string section, string name)
        {
            StringBuilder strSb = new StringBuilder(256);
            GetPrivateProfileString(section, name, "", strSb, 256, this.m_FileName);
            return strSb.ToString();
        }

        /// <summary>
        /// 写入指定值,如果不存在 节-键,则会自动创建
        /// </summary>
        /// <param name="section"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public void IniWriteValue(string section, string name, string value)
        {
            WritePrivateProfileString(section, name, value, this.m_FileName);
        }
    }
}
绘图 
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace _949CS//实时曲线绘制
{
    class draw
    {
        public List<Point> ptlist = new List<Point> { new Point(0, 0)};
        public PictureBox picbox = new PictureBox();
        public Bitmap mybitmap;//用于双缓冲的位图,和画布等大
        public Int32 xMoveToUp = 0, yMoveToRight = 0;     //X上移距离与Y右移距离
        public Int32 xToLeft = 5, xToRight = 10, yToUp = 5, yToDown = 5; //XY图像边距,x轴起点离左边距,终点右边距,y轴起点下边距,上边距,Y轴坐标为从上往下递增值
        public void DrawLineS(Color color, float Xmax, float Ymax)
        {
            if (ptlist.Count < 2)
            {//空返回
                return;
            }
            mybitmap = new Bitmap(picbox.Width, picbox.Height);//设定位图大小
            Graphics doublebufferg = Graphics.FromImage(mybitmap);//从位图上获取“画布”
            doublebufferg.Clear(Color.Black);//用背景色刷新

            //picbox填充为白色,便于显示图像  500*300
            Rectangle rect = new Rectangle(0, 0, picbox.Width, picbox.Height);
            doublebufferg.FillRectangle(new SolidBrush(Color.Black), rect);
             
            //画X和Y轴
            DrawXY(ref doublebufferg, picbox);
            //X轴上的刻度
            SetYAxis(ref doublebufferg, picbox, Ymax);
            //Y轴上的刻度
            SetXAxis(ref doublebufferg, picbox, Xmax);

            Point[] pt = ptlist.ToArray();
            Int32 i = 0;
            for (i = 0; i < pt.Length; i++)
            {
                pt[i].X += xToLeft + yMoveToRight;//自定义坐标转换
                pt[i].Y = picbox.Height - yToDown - xMoveToUp - pt[i].Y;
                if (i > 0)
                {
                    //要显示的实时曲线部分
                    doublebufferg.DrawLine(new Pen(color, 1), pt[i - 1], pt[i]);
                }
            }
            //将缓冲中的位图绘制到我们的窗体上
            if (!picbox.IsDisposed)
            {   //是够释放
                picbox.BackColor = Color.Black;     //背景色直接设置
                (picbox.CreateGraphics()).DrawImage(mybitmap, 0, 0);
            }
        } 
        //X上移
        public void  SetMoveX(Int32 x)
        {
            xMoveToUp = x;
        }
        //Y右移
        public void  SetMoveY(Int32 y)
        {
            yMoveToRight = y;
        }
        //完成X轴和Y轴的基本部分
        public void  DrawXY(ref Graphics g,PictureBox picbox)
        {
            Pen pen = new Pen(Color.White, 2);//画笔
            SolidBrush sb = new SolidBrush(Color.White);//话刷
            
            //X轴的箭头,实际上是绘制了一个三角形
            Int32 arrorWidth = 5, arrorHeight = 2;   //箭头的三角形中位线长与底边长一半
            Point[] xpts = new Point[3] {   //自定义坐标转换
                new Point(picbox.Width - (xToRight + arrorWidth), picbox.Height - (arrorHeight + yToDown + xMoveToUp)),
                new Point(picbox.Width - xToRight, picbox.Height - yToDown - xMoveToUp),
                new Point(picbox.Width - (xToRight + arrorWidth), picbox.Height + arrorHeight - yToDown - xMoveToUp)
                                        };

            g.DrawLine(pen, xToLeft, picbox.Height - yToDown - xMoveToUp, picbox.Width - xToRight, picbox.Height - yToDown - xMoveToUp);
            g.DrawPolygon(pen, xpts);//自定义坐标转换
            g.DrawString("X", new Font("宋体", 11), sb, picbox.Width - (xToRight), picbox.Height - (yToDown + xMoveToUp));

            //Y轴的箭头,实际上是绘制了一个三角形
            Point[] ypts = new Point[3] { //自定义坐标转换
                     new Point(xToLeft + yMoveToRight - arrorHeight, yToUp + arrorHeight),
                     new Point(xToLeft + yMoveToRight, yToUp), 
                     new Point(xToLeft + yMoveToRight + arrorHeight, yToUp + arrorHeight)
                      };

            g.DrawLine(pen, xToLeft + yMoveToRight, picbox.Height - yToDown, xToLeft + yMoveToRight, yToUp);
            g.DrawPolygon(pen, ypts);//自定义坐标转换
            g.DrawString("Y", new Font("宋体", 11), sb, yMoveToRight + xToLeft + arrorHeight, 0);
        
        }

        //绘制Y轴上的刻度
        public void SetYAxis(ref Graphics g,PictureBox picbox, float YMAX)
        {
            Pen p1 = new Pen(Color.Goldenrod, 1);
            Pen p2 = new Pen(Color.White, 2);
            SolidBrush sb = new SolidBrush(Color.White);

            float ykedu = YMAX / 200;//给定的最大刻度与实际像素的比例关系=,未优化,目前为1:1
            //第一个刻度的两个端点
            float xl = xToLeft - 3 + yMoveToRight, yl = picbox.Height - yToUp, xr = xToLeft + 3 + yMoveToRight, yr = picbox.Height - yToDown;//自定义坐标转换
            for (int j = 0; j < picbox.Height - (yToDown + yToUp); j += 10)
            {
                if (j % 50 == 0)//一个大的刻度,黑色,每隔50像素一个
                {
                    g.DrawLine(p2, xl, yl - j, xr, yl - j);//刻度线
                    string tempy = ((j - xMoveToUp - yToDown) * ykedu).ToString();//自定义坐标转换
                    g.DrawString(tempy, new Font("宋体", 8), sb, xl - 20, yl - j - 5);
                }
                else//小刻度,金黄色,10像素一个
                { g.DrawLine(p1, xl, yl - j, xr, yl - j); }
            }
        }



        //绘制x轴上的刻度
        public void SetXAxis(ref Graphics g,PictureBox picbox, float XMAX)
             {
              Pen p1 = new Pen(Color.Goldenrod, 1);
              Pen p2 = new Pen(Color.White, 2);
              SolidBrush sb = new SolidBrush(Color.White);

              float xkedu = XMAX / 400;  //比例关系未优化,目前为1:1
              float xt = xToLeft, yt = picbox.Height - yToDown - 3 - xMoveToUp, xb = xToLeft, yb = picbox.Height - yToDown + 3 - xMoveToUp;
              //自定义坐标转换
              for (int i = 0; i < picbox.Width - (xToLeft + xToRight); i += 10)
            {

                if (i % 50 == 0)
                {
                    g.DrawLine(p2, xt + i, yt, xb + i, yb);
                    string tempx = ((i - yMoveToRight - xToLeft) * xkedu).ToString();//自定义坐标转换
                    g.DrawString(tempx, new Font("宋体", 8), sb, xt + i - 7, picbox.Height - 25 - xMoveToUp);
                }
                else 
                { g.DrawLine(p1, xt + i, yt, xb + i, yb); }
            }
             }
        
        }

    }

CListCtrlEx重载 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace ADT_LISTVIEW
{
    enum LIST_TYPE
    {
        NO_TYPE = -1,
        EDIT_TYPE = 0,
        CBO_TYPE = 1,
    }
    class ListViewEx : ListView
    {
        private TextBox m_tb;
        private ComboBox m_cb;
        private bool m_bCheckBox;
        private Int32[ ] m_lst = new Int32[20];     //支持最大列数20
        private string[] m_str = new string[20];       //最大列字符串20
        public void SetChekBox(bool bCheck)
        { m_bCheckBox = bCheck; }
        public void AddCboString(String str) {
            string[] param = str.Split(':');
            m_cb.Items.Clear();
            foreach (string i in param)
            {
                m_cb.Items.Add(i);
            }
            m_cb.SelectedIndex = 0;
        }
        public void SetListType(int nIndex, int type)
        {
            m_lst[nIndex] = type;        }
        public int FindStringInCbo(int nCol, string str)
        {
            if (m_lst[nCol] != 1)
            {
                return -1;
            }
            else
            {
                AddCboString(m_str[nCol]);
                return m_cb.FindString(str, -1);
            }
        }
        public ListViewEx()
        {
            m_tb = new TextBox();
            m_cb = new ComboBox();
            m_tb.Multiline = false;
            m_tb.Visible = false;
            m_cb.Visible = false;
            m_cb.DropDownStyle = ComboBoxStyle.DropDownList;
            m_cb.IntegralHeight = true;
            this.GridLines = true;
            this.CheckBoxes = true;
            this.FullRowSelect = false;
            SetChekBox(this.CheckBoxes);
            this.Controls.Add(m_tb);
            this.Controls.Add(m_cb);
            for (int i = 0; i < 20; i++)
            {
                SetListType(i, 0);
            }
            SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);  //解决ListView闪烁问题
        }
        public void Insert(int nIndex, ListViewItem item)
        {
            for (int i = 0; i < item.SubItems.Count; i++ )
            {   //保存所有列字符——最多20
                m_str[i] = item.SubItems[i].Text;
                if (m_str[i].IndexOf(':') > 0)
                {
                    SetListType(i, 1);
                    AddCboString(m_str[i]);
                    item.SubItems[i].Text = m_cb.Text;
                }
                else
                {
                    SetListType(i, 0);
                }
            }
            this.Items.Insert(nIndex, item);
        }
        private void EditItem(ListViewItem.ListViewSubItem subItem)
        {
            if (this.SelectedItems.Count <= 0)
            {
                return;
            }
            Rectangle _rect = subItem.Bounds;
            m_tb.Bounds = _rect;
            ListViewItem lvi = this.SelectedItems[0];   //选中的多行第0行
            if (subItem == lvi.SubItems[0] || 0 == subItem.Bounds.X)
            {   //第一列为复选框
                if (m_bCheckBox)
                {
                    return;
                }
                else
                {   //修复宽度
                    m_tb.Width = this.Columns[0].Width;
                }
            }
            m_tb.BringToFront();
            m_tb.Text = subItem.Text;
            m_tb.Leave += new EventHandler(tb_Leave);
            m_tb.TextChanged += new EventHandler(m_tb_TextChanged);
            m_tb.Visible = true;
            m_tb.Tag = subItem;
            m_tb.Select();
        }

        private void EditItem(ListViewItem.ListViewSubItem subItem, Rectangle rt)
        {
            if (this.SelectedItems.Count <= 0)
            {
                return;
            }
            Rectangle _rect = rt;
            m_cb.Bounds = _rect;
            m_cb.BringToFront();
           // m_cb.Items.Add(subItem.Text);
            m_cb.Text = subItem.Text;
            m_cb.Leave += new EventHandler(lstb_Leave);
            m_cb.TextChanged += new EventHandler(m_lstb_TextChanged);
            m_cb.DropDownClosed += new EventHandler(m_lstb_TextChanged);
            m_cb.DropDown += new EventHandler(m_lstb_DropDown);
            m_cb.LostFocus += new EventHandler(lstb_Lost);
            m_cb.Visible = true;
            m_cb.Tag = subItem;
            m_cb.Select();
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
//             if (e.KeyCode == Keys.F2)
//             {
// 
//                 if (this.SelectedItems.Count > 0)
//                 {
//                     this.SelectedItems[1].BeginEdit();
//                     ListViewItem lvi = this.SelectedItems[0];
//                     EditItem(lvi.SubItems[0], new Rectangle(lvi.Bounds.Left, lvi.Bounds.Top, this.Columns[0].Width, lvi.Bounds.Height - 2));
//                 }
//             }
            base.OnKeyDown(e);
        }

        protected override void OnSelectedIndexChanged(EventArgs e)
        {
            this.m_tb.Visible = false;
            this.m_cb.Visible = false;
            base.OnSelectedIndexChanged(e);
        }
        protected override void OnDoubleClick(EventArgs e)
        {
            Point tmpPoint = this.PointToClient(Cursor.Position);
            ListViewItem.ListViewSubItem subitem = this.HitTest(tmpPoint).SubItem;
            ListViewItem item = this.HitTest(tmpPoint).Item;
            if (subitem != null)
            {
                int nIndex = 0;
                item.Checked = !item.Checked;       //修复双击时反选功能
                if (0 == subitem.Bounds.X)
                {//修复第一列
                    nIndex = 0;
                }
                else
                {
                    nIndex = this.SelectedItems[0].SubItems.IndexOf(subitem);
                    if (nIndex > this.Columns.Count)
                    {   //修复频繁点击时索引不更新bug
                        base.OnDoubleClick(e);
                        return;
                    }
                 }
                if (0 == m_lst[nIndex])
                 {  //类型选择,编辑框
                     EditItem(subitem);
                 }
                else if (1 == m_lst[nIndex])
                 {  //组合框
                     AddCboString(m_str[nIndex]);
                     EditItem(subitem, new Rectangle(subitem.Bounds.Left, subitem.Bounds.Top, this.Columns[nIndex].Width, subitem.Bounds.Height - 2));
                 }
                else
                {
                    ;
                }
                //item.Checked = !item.Checked;
            }
            base.OnDoubleClick(e);
        }
//         protected override void OnDrawColumnHeader(DrawListViewColumnHeaderEventArgs e)
//         {
//             m_cb.Hide();
//             base.OnDrawColumnHeader(e);
//         }
        protected override void WndProc(ref   Message m)
        {
            if (m.Msg == 0x115 || m.Msg == 0x114)
            {
                this.m_tb.Visible = false;
                this.m_cb.Visible = false;
            }
            base.WndProc(ref   m);
        }

        private void tb_Leave(object sender, EventArgs e)
        {
            m_tb.TextChanged -= new EventHandler(m_tb_TextChanged);
            (sender as TextBox).Visible = false;
        }

        private void m_tb_TextChanged(object sender, EventArgs e)
        {
            if ((sender as TextBox).Tag is ListViewItem.ListViewSubItem)
            {
                (this.m_tb.Tag as ListViewItem.ListViewSubItem).Text = this.m_tb.Text;
            }

        }
        private void lstb_Leave(object sender, EventArgs e)
        {
            m_cb.TextChanged -= new EventHandler(m_lstb_TextChanged);
            m_cb.DropDownClosed -= new EventHandler(m_lstb_TextChanged);
            m_cb.DropDownClosed -= new EventHandler(m_lstb_DropDown);
            m_cb.DropDown -= new EventHandler(m_lstb_DropDown);
            m_cb.LostFocus -= new EventHandler(lstb_Lost);
        }

        private void m_lstb_TextChanged(object sender, EventArgs e)
        {
            if ((sender as ComboBox).Tag is ListViewItem.ListViewSubItem)
            {
                (this.m_cb.Tag as ListViewItem.ListViewSubItem).Text = this.m_cb.Text;
            }
        }
        private void m_lstb_DropDown(object sender, EventArgs e)
        {
            if ((sender as ComboBox).Tag is ListViewItem.ListViewSubItem)
            {
                this.m_cb.Text = (this.m_cb.Tag as ListViewItem.ListViewSubItem).Text;
            }
        }
        private void lstb_Lost(object sender, EventArgs e)
        {
            m_cb.Hide();    //隐藏
            lstb_Leave(sender, e);
        }
        
    }
}

 

参考

FastTunnel: 开源免费跨平台 内网穿透 远程内网电脑 自定义域名访问内网站点 反向代理内网服务 http代理 类花生壳 端口转发 微信 小程序 frp NAT ssh proxy tunnel ngork

GitHub - HandyOrg/HandyControl: Contains some simple and commonly used WPF controls 

https://github.com/OfficeDev/Image-FileHandler

https://github.com/probot/no-response

https://github.com/dotnet/Open-XML-SDK

https://github.com/OfficeDev/PnP-WOPI

https://github.com/OfficeDev/Open-XML-SDK

https://github.com/OfficeDev/Excel-IO

GitHub - cnxy/files-uwp: A modern file explorer that pushes the boundaries of the platform.

GitHub - OfficeDev/office-fluent-ui-command-identifiers: Office Fluent User Interface Control Identifiers

Code of Conduct | Microsoft Open Source

https://github.com/CollaboratingPlatypus/PetaPoco

https://www.cnblogs.com/zhangweizhong/p/3718549.html

NuGet Gallery | PetaPoco 5.1.304

https://www.cnblogs.com/zhangweizhong/category/855479.html

https://www.cnblogs.com/zhangweizhong/category/771056.html

https://github.com/LonelyCodelang?tab=repositories

https://worktile.com/share/files/64a3b9c8ec0a4d3d81b89a630177c880

https://github.com/statianzo/PostLog

https://www.cnblogs.com/zhangweizhong/category/771055.html

https://github.com/statianzo/Fleck

https://github.com/EasyHttp/EasyHttp

GitHub - Tencent/xLua: xLua is a lua programming solution for C# ( Unity, .Net, Mono) , it supports android, ios, windows, linux, osx, etc.

QJ_FileCenter: 企捷Lotus文件管理平台是开源文档管理平台/企业网盘,支持企业文件、个人文件等文件分库管理,平台能够满足统一存储、文件共享功能。并提供文件上传、目录维护、重命名、移动、复制、删除、预览、等功能。

需ngnix反向代理,账号admin,密码abc123.搭建个人云盘

企捷科技 - 企捷科技

https://gitee.com/dotnetchina/BootstrapAdmin

dotNET China: 让 .NET 开发更简单,更通用,更流行。

GitHub - files-community/Files: Building the best file manager for Windows

GitHub - MMmmmoko/Bongo-Cat-Mver: An Bongo Cat overlay written in C++


创作不易,小小的支持一下吧!

  • 19
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
学生信息管理系统是一个常见的应用系统,使用C#语言采用三层架构进行开发,可以提高系统的可维护性、可扩展性、可重用性和可测试性等方面的优势。 三层架构是一个比较经典的软件架构,它将应用程序划分为三个主要的部分:表示层、业务逻辑层和数据访问层。每一层都有不同的职责,但它们又协同工作,为应用程序提供了良好的结构和可维护性。 下面我来介绍一下如何使用C#语言来开发一个学生信息管理系统。 一、需求分析 首先,我们需要对学生信息管理系统进行需求分析,明确系统的功能和需求,例如: 1. 学生信息的录入、修改、删除和查询功能。 2. 学生信息的显示和打印功能。 3. 学生信息的统计和分析功能。 4. 具有管理员和普通用户两种角色,管理员可以对学生信息进行管理,而普通用户只能浏览学生信息。 二、设计数据库 接下来,我们需要设计数据库,为系统提供数据存储和管理。在这里,我们可以使用SQL Server数据库管理系统来创建一个名为“Student”的数据库,其中包含一个名为“StudentInfo”的表,用于存储学生信息。 表的结构如下: |字段名称|字段类型|字段长度|是否允许空值| |:----:|:----:|:----:|:----:| |StudentID|nvarchar|10|否| |Name|nvarchar|20|否| |Sex|nvarchar|4|否| |Age|int|4|否| |Class|nvarchar|20|否| |Address|nvarchar|50|是| |Phone|nvarchar|20|是| 在这个表中,我们设置了一个主键StudentID,用于唯一标识每一个学生。 三、设计架构 在这里,我们采用三层架构来设计学生信息管理系统。 1. 表示层:表示层是系统与用户之间的接口,主要负责用户交互和数据展示的工作。在这里,我们使用Windows Forms技术来实现用户界面。 2. 业务逻辑层:业务逻辑层是系统的核心部分,它负责处理系统的业务逻辑,将用户的请求转化为对数据访问层的请求,并将处理结果返回给用户。在这里,我们将业务逻辑层封装为一个名为“StudentBLL”的类。 3. 数据访问层:数据访问层是系统与数据库之间的接口,主要负责对数据库进行访问和操作。在这里,我们将数据访问层封装为一个名为“StudentDAL”的类。 四、编写代码 1. 表示层代码 在表示层中,我们需要实现用户界面和事件响应等功能。在这里,我们使用Windows Forms技术来实现用户界面,例如: ```csharp // MainForm.cs public partial class MainForm : Form { private StudentBLL studentBLL = new StudentBLL(); public MainForm() { InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { RefreshData(); } private void RefreshData() { dgvStudent.DataSource = studentBLL.GetAllStudents(); } private void btnAdd_Click(object sender, EventArgs e) { AddStudentForm addStudentForm = new AddStudentForm(); if (addStudentForm.ShowDialog() == DialogResult.OK) { Student student = new Student(); student.StudentID = addStudentForm.txtStudentID.Text; student.Name = addStudentForm.txtName.Text; student.Sex = addStudentForm.cboSex.Text; student.Age = Convert.ToInt32(addStudentForm.txtAge.Text); student.Class = addStudentForm.txtClass.Text; student.Address = addStudentForm.txtAddress.Text; student.Phone = addStudentForm.txtPhone.Text; if (studentBLL.AddStudent(student)) { MessageBox.Show("添加成功!"); RefreshData(); } else { MessageBox.Show("添加失败,请检查输入信息!"); } } } private void btnEdit_Click(object sender, EventArgs e) { if (dgvStudent.CurrentRow != null) { EditStudentForm editStudentForm = new EditStudentForm(); editStudentForm.txtStudentID.Text = dgvStudent.CurrentRow.Cells["StudentID"].Value.ToString(); editStudentForm.txtName.Text = dgvStudent.CurrentRow.Cells["Name"].Value.ToString(); editStudentForm.cboSex.Text = dgvStudent.CurrentRow.Cells["Sex"].Value.ToString(); editStudentForm.txtAge.Text = dgvStudent.CurrentRow.Cells["Age"].Value.ToString(); editStudentForm.txtClass.Text = dgvStudent.CurrentRow.Cells["Class"].Value.ToString(); editStudentForm.txtAddress.Text = dgvStudent.CurrentRow.Cells["Address"].Value.ToString(); editStudentForm.txtPhone.Text = dgvStudent.CurrentRow.Cells["Phone"].Value.ToString(); if (editStudentForm.ShowDialog() == DialogResult.OK) { Student student = new Student(); student.StudentID = editStudentForm.txtStudentID.Text; student.Name = editStudentForm.txtName.Text; student.Sex = editStudentForm.cboSex.Text; student.Age = Convert.ToInt32(editStudentForm.txtAge.Text); student.Class = editStudentForm.txtClass.Text; student.Address = editStudentForm.txtAddress.Text; student.Phone = editStudentForm.txtPhone.Text; if (studentBLL.UpdateStudent(student)) { MessageBox.Show("修改成功!"); RefreshData(); } else { MessageBox.Show("修改失败,请检查输入信息!"); } } } else { MessageBox.Show("请先选择一条记录!"); } } private void btnDelete_Click(object sender, EventArgs e) { if (dgvStudent.CurrentRow != null) { string studentID = dgvStudent.CurrentRow.Cells["StudentID"].Value.ToString(); if (MessageBox.Show("确定要删除学号为" + studentID + "的学生信息吗?", "删除确认", MessageBoxButtons.YesNo) == DialogResult.Yes) { if (studentBLL.DeleteStudent(studentID)) { MessageBox.Show("删除成功!"); RefreshData(); } else { MessageBox.Show("删除失败!"); } } } else { MessageBox.Show("请先选择一条记录!"); } } private void btnSearch_Click(object sender, EventArgs e) { string keyword = txtKeyword.Text.Trim(); dgvStudent.DataSource = studentBLL.SearchStudents(keyword); } private void btnPrint_Click(object sender, EventArgs e) { PrintDialog printDialog = new PrintDialog(); if (printDialog.ShowDialog() == DialogResult.OK) { PrintDocument printDocument = new PrintDocument(); printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage); printDocument.PrinterSettings = printDialog.PrinterSettings; printDocument.Print(); } } private void printDocument_PrintPage(object sender, PrintPageEventArgs e) { Font font = new Font("宋体", 12, FontStyle.Regular); Brush brush = new SolidBrush(Color.Black); int x = e.MarginBounds.Left; int y = e.MarginBounds.Top; int rowHeight = dgvStudent.Rows[0].Height; int columnCount = dgvStudent.Columns.Count; for (int i = 0; i < columnCount; i++) { e.Graphics.DrawString(dgvStudent.Columns[i].HeaderText, font, brush, x, y); x += dgvStudent.Columns[i].Width; } y += rowHeight; for (int i = 0; i < dgvStudent.Rows.Count; i++) { x = e.MarginBounds.Left; for (int j = 0; j < columnCount; j++) { e.Graphics.DrawString(dgvStudent.Rows[i].Cells[j].Value.ToString(), font, brush, x, y); x += dgvStudent.Columns[j].Width; } y += rowHeight; } } } ``` 2. 业务逻辑层代码 在业务逻辑层中,我们需要实现系统的业务逻辑,例如: ```csharp // StudentBLL.cs public class StudentBLL { private StudentDAL studentDAL = new StudentDAL(); public DataTable GetAllStudents() { return studentDAL.GetAllStudents(); } public bool AddStudent(Student student) { if (studentDAL.GetStudentByID(student.StudentID) == null) { return studentDAL.AddStudent(student); } else { return false; } } public bool UpdateStudent(Student student) { if (studentDAL.GetStudentByID(student.StudentID) != null) { return studentDAL.UpdateStudent(student); } else { return false; } } public bool DeleteStudent(string studentID) { if (studentDAL.GetStudentByID(studentID) != null) { return studentDAL.DeleteStudent(studentID); } else { return false; } } public DataTable SearchStudents(string keyword) { return studentDAL.SearchStudents(keyword); } } ``` 3. 数据访问层代码 在数据访问层中,我们需要实现对数据库的访问和操作,例如: ```csharp // StudentDAL.cs public class StudentDAL { private string connectionString = ConfigurationManager.ConnectionStrings["Student"].ConnectionString; public DataTable GetAllStudents() { string sql = "SELECT StudentID, Name, Sex, Age, Class, Address, Phone FROM StudentInfo"; return SqlHelper.ExecuteDataTable(connectionString, CommandType.Text, sql); } public Student GetStudentByID(string studentID) { string sql = "SELECT StudentID, Name, Sex, Age, Class, Address, Phone FROM StudentInfo WHERE StudentID = @StudentID"; SqlParameter[] parameters = new SqlParameter[]{ new SqlParameter("@StudentID", studentID) }; DataTable dataTable = SqlHelper.ExecuteDataTable(connectionString, CommandType.Text, sql, parameters); if (dataTable.Rows.Count == 1) { Student student = new Student(); student.StudentID = dataTable.Rows[0]["StudentID"].ToString(); student.Name = dataTable.Rows[0]["Name"].ToString(); student.Sex = dataTable.Rows[0]["Sex"].ToString(); student.Age = Convert.ToInt32(dataTable.Rows[0]["Age"]); student.Class = dataTable.Rows[0]["Class"].ToString(); student.Address = dataTable.Rows[0]["Address"].ToString(); student.Phone = dataTable.Rows[0]["Phone"].ToString(); return student; } else { return null; } } public bool AddStudent(Student student) { string sql = "INSERT INTO StudentInfo(StudentID, Name, Sex, Age, Class, Address, Phone) VALUES(@StudentID, @Name, @Sex, @Age, @Class, @Address, @Phone)"; SqlParameter[] parameters = new SqlParameter[]{ new SqlParameter("@StudentID", student.StudentID), new SqlParameter("@Name", student.Name), new SqlParameter("@Sex", student.Sex), new SqlParameter("@Age", student.Age), new SqlParameter("@Class", student.Class), new SqlParameter("@Address", student.Address), new SqlParameter("@Phone", student.Phone) }; return SqlHelper.ExecuteNonQuery(connectionString, CommandType.Text, sql, parameters) == 1; } public bool UpdateStudent(Student student) { string sql = "UPDATE StudentInfo SET Name = @Name, Sex = @Sex, Age = @Age, Class = @Class, Address = @Address, Phone = @Phone WHERE StudentID = @StudentID"; SqlParameter[] parameters = new SqlParameter[]{ new SqlParameter("@StudentID", student.StudentID), new SqlParameter("@Name", student.Name), new SqlParameter("@Sex", student.Sex), new SqlParameter("@Age", student.Age), new SqlParameter("@Class", student.Class), new SqlParameter("@Address", student.Address), new SqlParameter("@Phone", student.Phone) }; return SqlHelper.ExecuteNonQuery(connectionString, CommandType.Text, sql, parameters) == 1; } public bool DeleteStudent(string studentID) { string sql = "DELETE FROM StudentInfo WHERE StudentID = @StudentID"; SqlParameter[] parameters = new SqlParameter[]{ new SqlParameter("@StudentID", studentID) }; return SqlHelper.ExecuteNonQuery(connectionString, CommandType.Text, sql, parameters) == 1; } public DataTable SearchStudents(string keyword) { string sql = "SELECT StudentID, Name, Sex, Age, Class, Address, Phone FROM StudentInfo WHERE StudentID LIKE '%' + @Keyword + '%' OR Name LIKE '%' + @Keyword + '%'"; SqlParameter[] parameters = new SqlParameter[]{ new SqlParameter("@Keyword", keyword) }; return SqlHelper.ExecuteDataTable(connectionString, CommandType.Text, sql, parameters); } } ``` 五、总结 通过以上的介绍,我们可以看到,采用C#语言和三层架构来开发学生信息管理系统可以提高系统的可维护性、可扩展性、可重用性和可测试性等方面的优势,同时也可以有效地分离业务逻辑和数据访问层,使系统的结构更加清晰和易于维护。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码力码力我爱你

创作不易,小小的支持一下吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值