效果如下图:
主要代码如下:
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 FuctionTest
{
public partial class FormProcessDataGridView : Form
{
BindingList<Employee> mEmployees = new BindingList<Employee>();
BindingSource mBbindingSource = new BindingSource();
public FormProcessDataGridView()
{
InitializeComponent();
}
private void FormInsertDataGridView_Load(object sender, EventArgs e)
{
mEmployees.Add(new Employee("Tom",23));
mEmployees.Add(new Employee("Harry",24));
mEmployees.Add(new Employee("John",26));
mBbindingSource.DataSource = mEmployees;
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView1.AutoGenerateColumns = false;
AddColumns();
dataGridView1.DataSource = mBbindingSource;
dataGridView1.CellClick +=
new DataGridViewCellEventHandler(dataGridView1_CellClick);
}
private void AddColumns()
{
DataGridViewTextBoxColumn nameColumn = new DataGridViewTextBoxColumn();
nameColumn.Name = "Name";
nameColumn.DataPropertyName = "Name";
DataGridViewTextBoxColumn ageColumn = new DataGridViewTextBoxColumn();
ageColumn.Name = "Age";
ageColumn.DataPropertyName = "Age";
DataGridViewButtonColumn insertColumn =
new DataGridViewButtonColumn();
insertColumn.HeaderText = "";
insertColumn.Name = "insertColumn";
insertColumn.Text = "插入";
insertColumn.UseColumnTextForButtonValue = true;
DataGridViewButtonColumn deleteColumn =
new DataGridViewButtonColumn();
deleteColumn.HeaderText = "";
deleteColumn.Name = "deleteColumn";
deleteColumn.Text = "删除";
deleteColumn.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Add(nameColumn);
dataGridView1.Columns.Add(ageColumn);
dataGridView1.Columns.Add(insertColumn);
dataGridView1.Columns.Add(deleteColumn);
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
//增加空行
if (e.ColumnIndex==2)
{
mEmployees.Insert(e.RowIndex,new Employee("", 0));
}
//删除当前行
if (e.ColumnIndex == 3)
{
mEmployees.RemoveAt(e.RowIndex);
}
}
列2输入格式验
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
MessageBox.Show(e.Exception.Message.ToString());
}
//对列1进行进一步验证
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex==0)
{
if (e.FormattedValue.ToString()=="123")
{
MessageBox.Show("不能为123");
e.Cancel = true;
dataGridView1.CancelEdit();
}
else
{
e.Cancel = false;
}
}
}
public class Employee
{
public Employee(String name)
{
nameValue = name;
}
public Employee(String name,int age)
{
nameValue = name;
ageValue = age;
}
private String nameValue;
public String Name
{
get { return nameValue; }
set { nameValue = value; }
}
public Employee Self
{
get { return this; }
}
private int? ageValue;
public int? Age
{
get { return ageValue; }
set { ageValue = value; }
}
}