After frequent search on almost all sites, I've failed to get a solution to the problem. My datagrid is bound to SQL server database using entity framework hence no MVVM pattern. The copy from datagrid seems to work with a few codes (seems inbuilt) but the paste has failed. The available solutions generate errors, ie datagrid doesn't contain a definition for selectedCell...
HOW BEST CAN I PASTE DATA FROM EXCEL TO WPF DATAGRID ENTITY FRAMEWORK BASED... I've tried this
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.C && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
// DataObject d = ClipboardHelper.ParseClipboardData(); Clipboard.SetDataObject(d);
}
if (e.Key == Key.V &&
(Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
// 2-dim array containing clipboard data
string[][] clipboardData =
((string)Clipboard.GetData(DataFormats.Text)).Split('\n')
.Select(row =>
row.Split('\t')
.Select(cell =>
cell.Length > 0 && cell[cell.Length - 1] == '\r' ?
cell.Substring(0, cell.Length - 1) : cell).ToArray())
.Where(a => a.Any(b => b.Length > 0)).ToArray();
// the index of the first DataGridRow
int startRow = ItemContainerGenerator.IndexFromContainer(
(DataGridRow)ItemContainerGenerator.ContainerFromItem(SelectedCells[0].Item));
int targetRowCount = SelectedCells.Count;
// the destination rows
// (from startRow to either end or length of clipboard rows)
DataGridRow[] rows =
Enumerable.Range(
startRow, Math.Min(Items.Count, targetRowCount))
.Select(rowIndex =>
ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow)
.Where(a => a != null).ToArray();
// the destination columns
// (from selected row to either end or max. length of clipboard colums)
DataGridColumn[] columns = Columns.OrderBy(column => column.DisplayIndex)
.SkipWhile(column => column != this.CurrentCell.Column)
.Take(clipboardData.Max(row => row.Length)).ToArray();
for (int rowIndex = 0; rowIndex < rows.Length; rowIndex++)
{
string[] rowContent = clipboardData[rowIndex % clipboardData.Length];
for (int colIndex = 0; colIndex < columns.Length; colIndex++)
{
string cellContent =
colIndex >= rowContent.Length ? "" : rowContent[colIndex];
columns[colIndex].OnPastingCellClipboardContent(
rows[rowIndex].Item, cellContent);
}
}
}
}
errors: 1. object doesnot contai a definition for IndexFromContainer and no extension containing IndexFromContainer can be found.
2.SelectedCells[0]
3.SelectedCells.Count
4.Usercontrol1 Doesnot contain a definition for CurrentCell and Items