我已经设置了一个窗体。目前它有一个 DataGridView 链接到 SQL Server 数据库中的单个表。我可以浏览表中的当前数据。
如何进行设置,以便用户可以将 Excel 工作表中的单列数据复制并粘贴到 DGV 中?
如果在 Excel 中,我在 A1 中有“x”,在 A2 中有“y”,那么在粘贴到 DGV 时必须保留行数,即对于本示例,它仍将超过 2 行
我试图从Code Project改编以下内容。if 失败就行 if (oCell.Value.ToString() != sCells[i])
with a NullReferenceException was unhandled
What is 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;
}
}