C#编程-81:DataGridView常用操作综合实例

简介: C#编程-81:DataGridView常用操作综合实例

image.png

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DataGridViewLastTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        DataTable dt;
        int valTotal = 500;//总数量       
        int valPerPage = 9;//每页条数
        int pageNum = 0;//总页数
        int currentPage = 1;//当前页
        int valCurrent = 0;//当前条数
        int valStartIndex = 0;//每页起始条数
        int valEndIndex = 0;//当前页终止条数
        //生成数据表
        private void GenerageData()
        {
            dt = new DataTable("ClerkSalary");
            dt.Columns.Add("姓名", Type.GetType("System.String"));
            dt.Columns.Add("姓别", Type.GetType("System.String"));
            dt.Columns.Add("工资", Type.GetType("System.Int32"));
            string familyName = "赵钱孙李周吴郑冯陈褚卫蒋沈韩杨朱秦尤许何吕施张";
            string lastName=@"那日丹桂梢头缀黄花绽竹篱抛情引墨顿成诗情也依依爱也依依
                            天涯两相望月人独伤悲红笺小字寄相思情也难追爱也难追
                            聊期花共月闲看绿着珠滴水涌泉歌诗儒词也狂书笔也狂书
                            瑶琴闲置久知音日渐疏往事思来总不如词也成枯笔也成枯";
            string gender = "男女";
            Random random = new Random();
            for (int i = 0; i < valTotal; i++)
            {
                //新增行方法一:
                //DataRow dr = dt.NewRow();
                //dr[0] = familyName[random.Next(0, familyName.Length)].ToString()
                //    + lastName[random.Next(0, lastName.Length)].ToString()
                //    + lastName[random.Next(0, lastName.Length)].ToString();
                //dr[1] = gender[random.Next(0, gender.Length)].ToString();
                //dr[2] = random.Next(1800, 10000);
                //dt.Rows.Add(dr);
                //新增行方法二:
                string name = familyName[random.Next(0, familyName.Length)].ToString()
                    +lastName[random.Next(0, lastName.Length)].ToString() 
                    +lastName[random.Next(0, lastName.Length)].ToString();
                string Gender=gender[random.Next(0,gender.Length)].ToString();
                int salary = random.Next(1800,10000);
                dt.Rows.Add(new object[] { name,Gender,salary});
            }
        }
        //加载当前页的数据
        private void LoadData()
        {
            DataTable dtTemp = dt.Clone();
            //只有一页
            if (currentPage == pageNum) valEndIndex = valTotal - 1;
            //不止一页
            else valEndIndex = currentPage * valPerPage;
            valStartIndex = valCurrent;
            //更新显示
            txtCurrentPage.Text = currentPage.ToString();
            lblTotalPage.Text = "/" + Convert.ToString(pageNum);
            //从数据表中读取当前数据
            for (int i = valStartIndex; i <= valEndIndex; i++)
            {
                dtTemp.ImportRow(dt.Rows[i]);
                valCurrent++;
            }
            //通过bindingSource1作为桥梁绑定数据
            bindingSource1.DataSource = dtTemp;
            bindingNavigator1.BindingSource = bindingSource1;
            dataGridView1.DataSource = bindingSource1;
            //设置不同行显示背景
            dataGridView1.RowsDefaultCellStyle.BackColor = Color.Pink;
            dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Violet;
        }
   private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                GenerageData();
                pageNum = (valTotal % valPerPage == 0) ? (valTotal / valPerPage) : (valTotal / valPerPage + 1);
                LoadData();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //绘制行号
            Rectangle rect = new Rectangle(e.RowBounds.Location.X,e.RowBounds.Location.Y,dataGridView1.RowHeadersWidth,e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,(e.RowIndex+1+valStartIndex).ToString(),dataGridView1.RowHeadersDefaultCellStyle.Font,rect,dataGridView1.RowHeadersDefaultCellStyle.ForeColor,TextFormatFlags.VerticalCenter|TextFormatFlags.Right);
            //选中时显示不同的背景
            if (e.RowIndex >= dataGridView1.Rows.Count - 1) return;
            var row =dataGridView1.Rows[e.RowIndex];
            Color oldForeColor = new Color();
            Color oldBackColor = new Color();
            if (row == dataGridView1.CurrentRow)
            {
                if (row.DefaultCellStyle.ForeColor != Color.White)
                {
                    oldForeColor = row.DefaultCellStyle.ForeColor;
                    row.DefaultCellStyle.ForeColor = Color.White;
                }
                if (row.DefaultCellStyle.BackColor != Color.Blue)
                {
                    oldBackColor = row.DefaultCellStyle.BackColor;
                    row.DefaultCellStyle.BackColor = Color.Blue;
                }
            }
            else
            {
                row.DefaultCellStyle.ForeColor = oldForeColor;
                row.DefaultCellStyle.BackColor = oldBackColor;
            }
        }
        private void bindingNavigator1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Text == "上一页")
            {
                currentPage--;
                if (currentPage <= 0)
                {
                    MessageBox.Show("已经是第一页");
                    currentPage++;
                    return;
                }
                else
                { 
                    valCurrent=valPerPage*(currentPage-1);
                }
                LoadData();
            }
            if (e.ClickedItem.Text =="下一页")
            {
                currentPage++;
                if (currentPage > pageNum)
                {
                    currentPage--;
                    MessageBox.Show("已经是最后一页");
                    return;
                }
                else
                {
                    valCurrent = valPerPage * (currentPage - 1);
                }
                LoadData();
            }
        }
    }
}
相关文章
|
3月前
|
C# 开发者
C# 一分钟浅谈:Code Contracts 与契约编程
【10月更文挑战第26天】本文介绍了 C# 中的 Code Contracts,这是一个强大的工具,用于通过契约编程增强代码的健壮性和可维护性。文章从基本概念入手,详细讲解了前置条件、后置条件和对象不变量的使用方法,并通过具体代码示例进行了说明。同时,文章还探讨了常见的问题和易错点,如忘记启用静态检查、过度依赖契约和性能影响,并提供了相应的解决建议。希望读者能通过本文更好地理解和应用 Code Contracts。
66 3
|
2月前
|
存储 安全 编译器
学懂C#编程:属性(Property)的概念定义及使用详解
通过深入理解和使用C#的属性,可以编写更清晰、简洁和高效的代码,为开发高质量的应用程序奠定基础。
122 12
|
3月前
|
设计模式 C# 图形学
Unity 游戏引擎 C# 编程:一分钟浅谈
本文介绍了在 Unity 游戏开发中使用 C# 的基础知识和常见问题。从 `MonoBehavior` 类的基础用法,到变量和属性的管理,再到空引用异常、资源管理和性能优化等常见问题的解决方法。文章还探讨了单例模式、事件系统和数据持久化等高级话题,旨在帮助开发者避免常见错误,提升游戏开发效率。
134 4
|
5月前
|
API C#
C# 一分钟浅谈:文件系统编程
在软件开发中,文件系统操作至关重要。本文将带你快速掌握C#中文件系统编程的基础知识,涵盖基本概念、常见问题及解决方法。文章详细介绍了`System.IO`命名空间下的关键类库,并通过示例代码展示了路径处理、异常处理、并发访问等技巧,还提供了异步API和流压缩等高级技巧,帮助你写出更健壮的代码。
72 2
|
4月前
|
安全 C# 数据安全/隐私保护
实现C#编程文件夹加锁保护
【10月更文挑战第16天】本文介绍了两种用 C# 实现文件夹保护的方法:一是通过设置文件系统权限,阻止普通用户访问;二是使用加密技术,对文件夹中的文件进行加密,防止未授权访问。提供了示例代码和使用方法,适用于不同安全需求的场景。
242 0
|
5月前
|
SQL 开发框架 安全
并发集合与任务并行库:C#中的高效编程实践
在现代软件开发中,多核处理器普及使多线程编程成为提升性能的关键。然而,传统同步模型在高并发下易引发死锁等问题。为此,.NET Framework引入了任务并行库(TPL)和并发集合,简化并发编程并增强代码可维护性。并发集合允许多线程安全访问,如`ConcurrentQueue&lt;T&gt;`和`ConcurrentDictionary&lt;TKey, TValue&gt;`,有效避免数据不一致。TPL则通过`Task`类实现异步操作,提高开发效率。正确使用这些工具可显著提升程序性能,但也需注意任务取消和异常处理等常见问题。
78 1
|
4月前
|
数据可视化 程序员 C#
C#中windows应用窗体程序的输入输出方法实例
C#中windows应用窗体程序的输入输出方法实例
84 0
|
5月前
|
安全 数据库连接 API
C#一分钟浅谈:多线程编程入门
在现代软件开发中,多线程编程对于提升程序响应性和执行效率至关重要。本文从基础概念入手,详细探讨了C#中的多线程技术,包括线程创建、管理及常见问题的解决策略,如线程安全、死锁和资源泄露等,并通过具体示例帮助读者理解和应用这些技巧,适合初学者快速掌握C#多线程编程。
106 0
|
9月前
|
开发框架 前端开发 .NET
C#编程与Web开发
【4月更文挑战第21天】本文探讨了C#在Web开发中的应用,包括使用ASP.NET框架、MVC模式、Web API和Entity Framework。C#作为.NET框架的主要语言,结合这些工具,能创建动态、高效的Web应用。实际案例涉及企业级应用、电子商务和社交媒体平台。尽管面临竞争和挑战,但C#在Web开发领域的前景将持续拓展。
265 3
|
9月前
|
SQL 开发框架 安全
C#编程与多线程处理
【4月更文挑战第21天】探索C#多线程处理,提升程序性能与响应性。了解C#中的Thread、Task类及Async/Await关键字,掌握线程同步与安全,实践并发计算、网络服务及UI优化。跟随未来发展趋势,利用C#打造高效应用。
241 3