https://blog.csdn.net/sanjiawan/article/details/6785394
https://blog.csdn.net/weixin_31026691/article/details/79448106
https://blog.csdn.net/rabbitsoft_1987/article/details/22949955
private void datagrid_LoadingRow(object sender, DataGridRowEventArgs e) { e.Row.Header = e.Row.GetIndex() + 1; }
private void datagrid_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { UIElement elementWithFocus = Keyboard.FocusedElement as UIElement; if (elementWithFocus == null) return; e.Handled = true; if (this.datagrid.CurrentCell.Column.DisplayIndex == this.datagrid.Columns.Count - 1) { this.datagrid.CommitEdit(DataGridEditingUnit.Row, exitEditingMode: true); elementWithFocus = Keyboard.FocusedElement as UIElement; } if (elementWithFocus != null) { elementWithFocus.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); } } } private void datagrid_KeyDown(object sender, KeyEventArgs e) { datagrid.CanUserAddRows = false; if (ModifierKeys.Control == Keyboard.Modifiers && e.Key == Key.V) { DataGirdViewCellPaste(); } } #region ctrl+c粘贴 private void DataGirdViewCellPaste() { try { // 获取剪切板的内容,并按行分割 string pasteText = Clipboard.GetText(); if (string.IsNullOrEmpty(pasteText)) 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); } //获取获取当前选中单元格所在的行序号 int rowindex = datagrid.SelectedIndex; } catch { MessageBox.Show("粘贴区域大小不一致"); return; } } #endregion private void btn_add_Click(object sender, RoutedEventArgs e) { this.datagrid.CanUserAddRows = true; }