基本信息
源码名称:C#dataGridView控件增删查改实例
源码大小:0.19M
文件格式:.zip
开发语言:C#
更新时间:2020-04-02
   源码介绍

这篇文章(https://www.daboke.com)主要介绍了C#dataGridView控件的增删查改操作、自动生成序列号和末行显示等知识,并提供"仓库物料实时监控模拟"实例给大家进行学习参考。



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 datagridview
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.textBox1.KeyDown  = new KeyEventHandler(textBox1_KeyDown);//
        }

        System.Timers.Timer t = new System.Timers.Timer(2000);//实例化Timer类,设置间隔时间为2000毫秒;
        
        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.AllowUserToAddRows = false;//不显示dataGridView1的最后一行空白              
            t.Elapsed  = new System.Timers.ElapsedEventHandler(creatdata);//到达时间的时候执行事件;
            t.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
            t.Start();//启动定时器
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            t.Stop();//停止定时器
            t.Close();//关闭定时器
        }

        private void Button3_Click(object sender, EventArgs e)
        {
            //清空所有行
            while (this.dataGridView1.Rows.Count != 0)
            {
                this.dataGridView1.Rows.RemoveAt(0);
            }
        }

        /// <summary>
        /// dataGridView1添加数据的方法
        /// </summary>
        /// <param name="column1"></param>
        /// <param name="column2"></param>
        /// <param name="column3"></param>
        /// <param name="column4"></param>
        /// <param name="column5"></param>
        /// <param name="column6"></param>
        /// <param name="column7"></param>
        /// <param name="column8"></param>
        public void additem(DateTime column1, string column2, double column3, double column4, double column5, double column6,
           double column7, int column8)
        {                     
            //此处的代码不能进行循环!必须封装为一个方法,通过方法的循环,才能实现循环!
            DataGridViewRow dgvr = new DataGridViewRow();
            foreach (DataGridViewColumn c in this.dataGridView1.Columns)
            {
                dgvr.Cells.Add(c.CellTemplate.Clone() as DataGridViewCell);
            }
            dgvr.Cells[0].Value = column1;
            dgvr.Cells[1].Value = column2;
            dgvr.Cells[2].Value = column3;
            dgvr.Cells[3].Value = column4;
            dgvr.Cells[4].Value = column5;
            dgvr.Cells[5].Value = column6;
            dgvr.Cells[6].Value = column7;
            dgvr.Cells[7].Value = column8;
            this.dataGridView1.Rows.Add(dgvr);
            this.dataGridView1.RowPostPaint  = new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(DgvGradeInfoRowPostPaint);//调用DgvGradeInfoRowPostPaint方法
            this.dataGridView1.FirstDisplayedScrollingRowIndex = this.dataGridView1.Rows.Count - 1;//DataGridview控件自动下拉到最后一行
        }

        /// <summary>
        /// 生成随机数据的方法
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        public void creatdata(object source, System.Timers.ElapsedEventArgs e)
        {
            DateTime dt = DateTime.Now;
            string product;
            double length, width, height, weight, price;
            int quantity;
            string letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";//需要随机的字母
            Random rd = new Random(); //随机类
            product = "";
            for (int i = 0; i < 6; i  ) //循环6次,生成6位数字,n位就循环n次
            {
                product  = letter[rd.Next(52)]; //通过索引下标随机
            }
            length = GetRandomNumber(100, 200, 2);
            width = GetRandomNumber(30, 50, 2);
            height = GetRandomNumber(5, 10, 2);
            weight = GetRandomNumber(1000,10000, 2);
            price = GetRandomNumber(5000, 25000, 2);
            quantity = rd.Next(0,100);
            additem(dt, product, length, width, height, weight, price, quantity);//dataGridView添加随机数据           
        }

        /// <summary>
        /// 获取随机小数的方法
        /// </summary>
        /// <param name="minimum"></param>
        /// <param name="maximum"></param>
        /// <param name="Len"></param>
        /// <returns></returns>
        public double GetRandomNumber(double minimum, double maximum, int Len)   //Len小数点保留位数
        {
            Random random = new Random();
            return Math.Round(random.NextDouble() * (maximum - minimum)   minimum, Len);
        }
     
        /// <summary>
        /// dataGridView自动生成序列号的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DgvGradeInfoRowPostPaint(object sender, System.Windows.Forms.DataGridViewRowPostPaintEventArgs e)
        {
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(e.RowBounds.Location.X,
                e.RowBounds.Location.Y,
                this.dataGridView1.RowHeadersWidth - 4,
                e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex   1).ToString(),
                this.dataGridView1.RowHeadersDefaultCellStyle.Font,
                rectangle,
                this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        /// <summary>
        /// dataGridView删除选中行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button4_Click(object sender, EventArgs e)
        {        
            int row = dataGridView1.SelectedRows.Count;
            if (row == 0)
            {
                MessageBox.Show("没有选中任何行", "Error");
                return;
            }
            else if (MessageBox.Show("确认删除选中的"   row.ToString()   "条记录吗?", "请确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                for (int i = 0; i < dataGridView1.SelectedRows.Count; i  )
                {
                    dataGridView1.Rows.Remove(dataGridView1.SelectedRows[i]);//有时会报错,显示:索引超出范围。必须为非负值并小于集合大小。
                                                                             //dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[i].Index);//语句也可以这样写
                    i--;
                }
            }
        }

        /// <summary>
        /// copy生成随机数据的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button5_Click(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            string product;
            double length, width, height, weight, price;
            int quantity;

            string letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";//需要随机的字母
            Random rd = new Random(); //随机类
            product = "";
            for (int i = 0; i < 6; i  ) //循环6次,生成6位数字,n位就循环n次
            {
                product  = letter[rd.Next(52)]; //通过索引下标随机
            }

            length = GetRandomNumber(100, 200, 2);
            width = GetRandomNumber(30, 50, 2);
            height = GetRandomNumber(5, 10, 2);
            weight = GetRandomNumber(1000, 10000, 2);
            price = GetRandomNumber(5000, 25000, 2);
            quantity = rd.Next(0, 100);

            additem(dt, product, length, width, height, weight, price, quantity);
        }
        /// <summary>
        /// dataGridView查找数据的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            int row = dataGridView1.Rows.Count;//得到总行数
            int cell = dataGridView1.Rows[1].Cells.Count;//得到总列数
            for (int i = 0; i < row; i  )//得到总行数并在之内循环
            {
                for (int j = 0; j < cell; j  )//得到总列数并在之内循环
                {
                    if (textBox1.Text == dataGridView1.Rows[i].Cells[j].Value.ToString())
                    {   //对比TexBox中的值是否与dataGridView中的值相同(上面这句)
                        this.dataGridView1.CurrentCell = this.dataGridView1[j, i];//定位到相同的单元格
                        return;//返回
                    }

                }
            }

        }
        private void Button6_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("IEXPLORE.EXE", "https://www.daboke.com");//欢迎访问大博客!
        }

        private void Button7_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("IEXPLORE.EXE", "https://www.daboke.com/program/datagridview");//原文地址!
        }     
    }   
}