Copy Paste From Grid View to Excel File Provide Easy Ways for Reporting and Graphs Making.Excel File Copy Paste To Grid View Save Data Entry Operator Time and After Pasting Data To Data Grid View We can Easily Save it To Data Base Just by clicking Button.
So lets start
First Drag Drop an Data Grid View on Windows Forms
Create Columns in Data Grid View ID ,StudentName, Class,Sec,Batch,Fees.
First We enable Grid View to Copy data In Clip Board by writing Following line in Page load Event.
this.dataGridView1.ClipboardCopyMode =
DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
and Write Download The Following Method For Copy Paste.
private void PasteClipboard()
{
try
{
string s = Clipboard.GetText();
string[] lines = s.Split('\n');
int iFail = 0, iRow = dataGridView1.CurrentCell.RowIndex;
int iCol = dataGridView1.CurrentCell.ColumnIndex;
DataGridViewCell oCell;
foreach (string line in lines)
{
if (iRow < dataGridView1.RowCount && line.Length > 0)
{
string[] sCells = line.Split('\t');
for (int i = 0; i < sCells.GetLength(0); ++i)
{
if (iCol + i < this.dataGridView1.ColumnCount)
{
oCell = dataGridView1[iCol + i, iRow];
if (!oCell.ReadOnly)
{
oCell.Value = Convert.ChangeType(sCells[i],
oCell.ValueType);
oCell.Style.BackColor = Color.Tomato;
}
}
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;
}
}
Now Write Some Code Behid in
dataGridView1_MouseClick Event For Display The Context
menu
if (e.Button == MouseButtons.Right)
{
ContextMenu m = new ContextMenu();
m.MenuItems.Add(new MenuItem("Paste"),, new EventHandler(BtPasteClick));
var relativeMousePosition = dataGridView1.PointToClient(Cursor.Position);
m.Show(dataGridView1, relativeMousePosition);
}
and also Add Following Method same as it is After Above Method
private void BtPasteClick(object sender, EventArgs e)
{
string s = Clipboard.GetText();
if (s.Length > 0)
{
PasteClipboard();
}
else
{
MessageBox.Show("Please Copy Some Data First "
, "[MOHAMMAD SAJJAD ASHRAF AWAN]"
, MessageBoxButtons.OK, MessageBoxIcon.Question);
}
}
So that it .
When You Copy Paste Data Always Remember Following Things .
1) Always Copy Equal Number of Cells mean When you Copy Data from Excel Must Copy equal or Less No. of Cells According to Data Grid view .
2)You Must Add No .of Empty Row to Grid view That you are Going to Paste.
3)always select Initial Cell of Grid View to Paste Data.
DOWNLOAD SOURCE CODE
SOME OUTPUT SCREEN SHORTS