複製是GridControl自帶的屬性,主要解決的是多個單元格複製的問題,這裏涉及到兩個參數
主要是粘貼的
先定義兩個全局變量,在單元格點擊事件的時候獲取單元格的行號和列號
//獲取當前選中單元格所在的列序號
int curntindex;
//獲取獲取當前選中單元格所在的行序號
int rowindex;
private void GV_RowCellClick(object sender, RowCellClickEventArgs e)
{
//獲取當前選中單元格所在的列序號
curntindex = e.Column.ColumnHandle;
//獲取獲取當前選中單元格所在的行序號
rowindex = e.RowHandle;
//MessageBox.Show(curntindex.ToString());
//MessageBox.Show(rowindex.ToString());
}
然後定義個函數,對剪切板的數據進行格式處理
private void Paste()
{
try
{
GridControl x = (GridControl)gridControl1;
DataTable dt = x.DataSource as DataTable;
// 獲取剪切板的內容,並按行分割
string pasteText = Clipboard.GetText();
MessageBox.Show(pasteText);
if (string.IsNullOrEmpty(pasteText))
{
MessageBox.Show("剪切板內容爲空,請重新複製!");
return;
}
int tnum = 0;
int nnum = 0;
//獲得當前剪貼板內容的行、列數
for (int i = 0; i < pasteText.Length; i++)
{
if (pasteText.Substring(i, 1) == "\t")
{
tnum++;
}
if (pasteText.Substring(i, 1) == "\n")
{
nnum++;
}
}
Object[,] data;
//粘貼板上的數據來自於EXCEL時,每行末都有\n,在DATAGRIDVIEW內複製時,最後一行末沒有\n
if (pasteText.Substring(pasteText.Length - 1, 1) == "\n")
{
nnum = nnum - 1;
}
tnum = tnum / (nnum + 1);
data = new object[nnum + 1, tnum + 1];//定義一個二維數組
String rowstr;
rowstr = "";
//MessageBox.Show(pasteText.IndexOf("B").ToString());
//對數組賦值
for (int i = 0; i < (nnum + 1); i++)
{
for (int colIndex = 0; colIndex < (tnum + 1); colIndex++)
{
//一行中的最後一列
if (colIndex == tnum && pasteText.IndexOf("\r") != -1)
{
rowstr = pasteText.Substring(0, pasteText.IndexOf("\r"));
}
//最後一行的最後一列
if (colIndex == tnum && pasteText.IndexOf("\r") == -1)
{
rowstr = pasteText.Substring(0);
}
//其他行列
if (colIndex != tnum)
{
rowstr = pasteText.Substring(0, pasteText.IndexOf("\t"));
pasteText = pasteText.Substring(pasteText.IndexOf("\t") + 1);
}
data[i, colIndex] = rowstr;
}
//截取下一行數據
pasteText = pasteText.Substring(pasteText.IndexOf("\n") + 1);
}
for (int j = 0; j < (nnum + 1); j++)
{
for (int colIndex = 0; colIndex < (tnum + 1); colIndex++)
{
this.GV.GetDataRow(j + rowindex)[colIndex + curntindex] = data[j, colIndex];
//GV.Rows[j + rowindex].Cells[colIndex + curntindex].Value = data[j, colIndex];
}
}
//string[] lines = pasteText.Split(new char[] { ' ', ' ' });
//string s = String.Join("' '", lines);
//MessageBox.Show(s);
//foreach (string line in lines)
//{
// if (string.IsNullOrEmpty(line.Trim()))
// continue;
// // 按 Tab 分割數據
// string[] vals = line.Split(' ');
// dt.Rows.Add(vals);
}
catch
{
// 不處理
}
}
然後在GridView的KeyDown事件設置粘貼快捷鍵Ctrl+V
private void Grid_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Control == true) && e.KeyCode == Keys.V)
{
Paste();
}
}