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


    .net 2005下的Windows Form Application,一个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);                         //添加的行作为最后一行
            }
        }
    }

    缠非缠、禅非禅 枯木龙吟照大千
  • 相关阅读:
    从输入网址到显示网页简介
    java异常及日志注意事项
    java-Excel导出中的坑
    python-arcade时钟
    tkinter-clock实例
    http远程调用原生get、post模板
    eclipse使用小技巧
    sublime text3安装Package Control和Vue Syntax Highlight
    双十一剁手了吗
    Nginx配置HTTPS
  • 原文地址:https://www.cnblogs.com/soany/p/5306259.html
Copyright © 2020-2023  润新知