02
4月
2020

C#dataGridView控件增删查改实例

dataGridView是Winform中的一个列表展示控件,其展示效果类似于excel表格,我们经常用它来对数据进行操作,学习dataGridView控件的用法对数据处理等方面的开发有很大的帮助。今天我来给大家演示一下如何对dataGridView控件进行增删查改操作,以及通过实例展示dataGridView的显示效果。

首先我们需要在窗体中新建一个dataGridView控件,选中控件右键点”添加列”来定义列的属性,图1是我设计的仓库物料实时监控模拟应用,使用定时器生成随机数据并添加到dataGridView中,涉及到dataGridView的增删查改、自动生成序列号和末行显示等知识。

interface

图1-dataGridView控件应用实例界面

1.dataGridView添加数据

我们可以通过新建一个additem方法向datagridview添加数据:

/// <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);
}

2.dataGridView删除数据

使用for循环统计选中的dataGridView行数并删除,注意这里只是对dataGridView删除多行而不是从数据库中删除。

/// <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--;
        }
    }
}

3.dataGridView查找数据

在textBox的KeyDown事件中嵌套两层for循环定位关键字在dataGridView中的行和列,在文本框中输入关键字按回车即可精确定位。

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;//返回
                   }

               }
           }

       }

4.dataGridView改动数据

选中需要改动的dataGridView单元格双击或者按F2,即可进入编辑模式直接进行修改。

小知识:把dataGridView控件的EditCellOnEnter 属性设为True,当鼠标移动到单元格后可立即切换到编辑模式,按ESC取消编辑。

5.dataGridView自动生成序列号

这里需要使用dataGridView的RowPostPaint事件,使用前需要进行声明。

this.dataGridView1.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(DgvGradeInfoRowPostPaint);//调用DgvGradeInfoRowPostPaint方法
/// <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);
}

6.dataGridView末行显示

this.dataGridView1.FirstDisplayedScrollingRowIndex = this.dataGridView1.Rows.Count - 1;//DataGridview控件自动下拉到最后一行

7.dataGridView一键清空

直接使用while判断行数是否为0,不为0时删除所有行。

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

代码全文:

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");//原文地址!
        }     
    }   
}

代码链接:

datagridview

原文链接:

https://www.daboke.com/program/datagridview.html

You may also like...

发表评论

邮箱地址不会被公开。

微信 OR 支付宝 扫描二维码
为本文作者 打个赏
pay_weixin pay_weixin
最喜欢你一言不合就打赏的样子了^_^