.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); //添加的行作为最后一行
}
}
}