WinForm DataGridView 可编辑单元格拷贝

1.Form1_Load中绑定数据源

DataTable Data = new DataTable();

Data.Columns.Add("id",typeof(int));

……

//设为false,否则ColId.Index 总是0

dgSource.AutoGenerateColumns = false;

dgSource.DataSource = Data;


dgSource.AllowUserToAddRows = true;


2.添加DataError事件

private void dgSource_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
	e.Cancel = true;
}

2.KeyDown事件处理

//拷贝
if (e.Control && e.KeyCode == Keys.C)
{

    //单个单元格使用系统默认行为
	if (dgSource.SelectedCells.Count == 0 || dgSource.SelectedCells.Count == 1) return;

	Dictionary<string, Dictionary<string, object>> data = new Dictionary<string, Dictionary<string, object>>();

	string rkey = null;
	foreach (DataGridViewCell cell in dgSource.SelectedCells)
	{
		rkey = cell.RowIndex.ToString();
		if (!data.ContainsKey(rkey))
		{
			data.Add(rkey, new Dictionary<string, object>());
		}

		data[rkey][cell.OwningColumn.DataPropertyName] = cell.Value;
	}
    //行排一下序
	data = data.OrderBy(d => int.Parse(d.Key)).ToDictionary(d => d.Key, d => d.Value);
    //保存为json格式
	Clipboard.SetText(Newtonsoft.Json.JsonConvert.SerializeObject(data));
	e.Handled = true;
}
else if (e.Control && e.KeyCode == Keys.V)
{
	string text = Clipboard.GetText();

	if (dgSource.SelectedCells.Count == 0 || string.IsNullOrEmpty(text)) return;

	//拷贝
	if (dgSource.SelectedCells.Count == 1) {
		try
		{
			dgSource.BeginEdit(false);
			dgSource.CurrentCell.Value = text;
			//如果是最后一行,会自动新增一行
			dgSource.NotifyCurrentCellDirty(true);
		}
		finally
		{
			dgSource.EndEdit();
		}
		e.Handled = true;
		return;
	}

	int columnIndex = -1;
	bool isNewRow = false;

	List<DataGridViewCell> list = null;
	Dictionary<int, List<DataGridViewCell>> cells = new Dictionary<int, List<DataGridViewCell>>();
	foreach (DataGridViewCell cell in dgSource.SelectedCells)
	{
		if (!cells.ContainsKey(cell.RowIndex))
		{
			if (columnIndex == -1 && cell.RowIndex == dgSource.NewRowIndex)
			{
				columnIndex = cell.ColumnIndex;
				isNewRow = true;
			}

			if (list != null)
			{
				list.Sort((a, b) => a.ColumnIndex.CompareTo(b.ColumnIndex));
			}
			list = new List<DataGridViewCell>();
			cells.Add(cell.RowIndex, list);
		}
		cells[cell.RowIndex].Add(cell);
	}

	list.Sort((a, b) => a.ColumnIndex.CompareTo(b.ColumnIndex));

	cells = cells.OrderBy(k => k.Key).ToDictionary(k => k.Key, k => k.Value);
	
	Dictionary<string, Dictionary<string, object>> data = null;
	
	try
	{
	    //本程序的拷贝数据 json格式
		data = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, object>>>(text);
		if (data != null)
		{
			string[] rows = data.Keys.ToArray();
			int[] selectedRows = cells.Keys.ToArray();
			for (int i = 0, j = 0; i < rows.Length && i < selectedRows.Length && j < cells[selectedRows[i]].Count;)
			{
				if (columnIndex == -1 && cells[selectedRows[i]][j].RowIndex == dgSource.NewRowIndex)
				{
					columnIndex = cells[selectedRows[i]][j].ColumnIndex;
					isNewRow = true;
				}

				if (data[rows[i]].ContainsKey(cells[selectedRows[i]][j].OwningColumn.DataPropertyName))
				{
					cells[selectedRows[i]][j].Value = data[rows[i]][cells[selectedRows[i]][j].OwningColumn.DataPropertyName];
				}
				j++;
				if (j == cells[selectedRows[i]].Count)
				{
					j = 0;
					i++;
				}
			}

			e.Handled = true;
		}
	}
	catch
	{
	    //表格拷贝数据
		string[] strs = text.Split(new string[] { Environment.NewLine, "\n", "\r" }, StringSplitOptions.None);
		string[] cls = null;

		int[] rows = cells.Keys.ToArray();

		for (int i = 0; i < strs.Length && i < rows.Length;i++)
		{
			cls = strs[i].Split('\t');
			for (int j = 0; j < cells[rows[i]].Count && j < cls.Length; j++)
			{
				cells[rows[i]][j].Value = cls[j];
			}
		}
		e.Handled = true;
	}

	if (isNewRow)
	{
		dgSource.CurrentCell = dgSource.Rows[dgSource.NewRowIndex].Cells[columnIndex];
		//切换当前单元格为最后一行的某编辑单元格,切换编辑状态,可以使最后一行继续添加一行
		dgSource.BeginEdit(false);
		dgSource.EndEdit(); 
		dgSource.NotifyCurrentCellDirty(true);
		
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

闪耀星星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值