DataGridView添加一行数据、全选、取消全选、清空数据、删除选中行

一个DataGridView控件和4个Button

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Wind
{
    public partial class Form1 : Form
    {

        int c = 1;

        public Form1()
        {
            InitializeComponent();
        }


        //全选或取消全选
        private void btn_SelectAll(object sender, EventArgs e)
        {
            int selectedRows = dgv.SelectedRows.Count;
            if (selectedRows == dgv.Rows.Count)
            {
                foreach (DataGridViewRow dr in dgv.SelectedRows)
                {
                    dr.Selected = false;
                }
            }
            else
                dgv.SelectAll();
        }

        //清空所有记录
        private void btn_Clear(object sender, EventArgs e)
        {
            dgv.Rows.Clear();
        }

        //删除所有选中的行
        private void btn_deleteSelectedRows(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dr in dgv.SelectedRows)
            {
                if(dr.IsNewRow == false)//如果不是已提交的行,默认情况下在添加一行数据成功后,DataGridView为新建一行作为新数据的插入位置
                    dgv.Rows.Remove(dr);
            }
        }

        //添加一行新记录
        private void btn_addOneRecord_Click(object sender, EventArgs e)
        {
            DataGridViewRow dr = new DataGridViewRow();
            dr.CreateCells(dgv);
            dr.Cells[0].Value = "h" + c.ToString();
            dr.Cells[1].Value = (c++);
            dgv.Rows.Insert(0, dr);                     //添加的行作为第一行
            //dgv.Rows.Add(dr);                         //添加的行作为最后一行
        }
    }
}

 
 
posted @ 2017-09-15 10:10  dexin  阅读(5002)  评论(0编辑  收藏  举报