首先要设置GridControl中的OptionSelection中的Multiselect为true,并且设置MultiSelectMode为cell
然后设置两个全局变量,用来在RowCellClick事件中指明所点击的cell所在的行数
//获取当前选中单元格所在的列序号int curntindex;//获取获取当前选中单元格所在的行序号int rowindex;private void SetClickIndex(RowCellClickEventArgs e){//获取当前选中单元格所在的列序号curntindex = e.Column.ColumnHandle;//获取获取当前选中单元格所在的行序号rowindex = e.RowHandle;}private void gridView4_RowCellClick(object sender, RowCellClickEventArgs e){SetClickIndex(e);}
粘贴Excel的代码
private void Paste(GridView gridView){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内复制时,最后一行末没有\nif (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++){gridView.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{// 不处理}}
之后便可以在KeyDown事件按下Ctrl+V的时候粘贴上去
private void gridView4_KeyDown(object sender, KeyEventArgs e){GridView gv = (GridView)sender;if ((e.Control == true) && e.KeyCode == Keys.V){Paste(gv);}}
