I’ve set a windowsform up.
Currently it it has a single DataGridView that is linked to a single table in a SQL Server db.
I can browse the current data in the table.
How do I set things up so that a user can copy and paste a single column of data from an Excel sheet into the DGV ?
If, in Excel I have ‘x’ in A1 and ‘y’ in A2 then this must preserve the number of rows when pasted into the DGV i.e for this example it would still be over 2 rows
I’ve tried to adapt the following from Code Project. If fails on the line if (oCell.Value.ToString() != sCells[i]) with a NullReferenceException was unhandled What am I doing wrong?
private void uxChargeBackDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
PasteClipboard();
//uxChargeBackDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Clipboard.GetText();
}
private void PasteClipboard()
{
try
{
string s = Clipboard.GetText();
string[] lines = s.Split('\n');
int iFail = 0, iRow = uxChargeBackDataGridView.CurrentCell.RowIndex;
int iCol = uxChargeBackDataGridView.CurrentCell.ColumnIndex;
DataGridViewCell oCell;
foreach (string line in lines)
{
if (iRow < uxChargeBackDataGridView.RowCount && line.Length > 0)
{
string[] sCells = line.Split('\t');
for (int i = 0; i < sCells.GetLength(0); ++i)
{
if (iCol + i < this.uxChargeBackDataGridView.ColumnCount)
{
oCell = uxChargeBackDataGridView[iCol + i, iRow];
if (!oCell.ReadOnly)
{
if (oCell.Value.ToString() != sCells[i])
{
oCell.Value = Convert.ChangeType(sCells[i],
oCell.ValueType);
oCell.Style.BackColor = Color.Tomato;
}
else
iFail++;
//only traps a fail if the data has changed
//and you are pasting into a read only cell
}
}
else
{ break; }
}
iRow++;
}
else
{ break; }
if (iFail > 0)
MessageBox.Show(string.Format("{0} updates failed due" +
" to read only column setting", iFail));
}
}
catch (FormatException)
{
MessageBox.Show("The data you pasted is in the wrong format for the cell");
return;
}
}
Very simple and will do the trick:
edit*
If you want to paste into multple cells and not a single cell then check out this blog post:
http://happysoftware.blogspot.co.uk/2011/07/c-code-snippet-paste-to-datagridview.html