Thursday, October 8, 2009

c# copy excel data and paste into datagridview table

This post is about managing the memory data object after ctrl+c is used in Excel. You will learn how data are organised in memory and should be able to apply it anywhere. The code example tries to read the data in DataObject out and paste it in datagridview.            

DataObject o = (DataObject) Clipboard.GetDataObject(); 
if (o.GetDataPresent(DataFormats.Text))
int rowOfInterest = DataGridView.CurrentCell.RowIndex;
string[] selectedRows = Regex.Split(o.GetData(DataFormats.Text).ToString( ).TrimEnd( "\r\n".ToCharArray() ), "\r\n");

if (selectedRows == null || selectedRows.Length == 0)

foreach (string row in selectedRows)
if (rowOfInterest >= DataGridView.Rows.Count)

string[] data = Regex.Split(row, "\t");
int col = DataGridView.CurrentCell.ColumnIndex;

foreach (string ob in data)
if (col >= DataGridView.Columns.Count)
if (ob!=null)
DataGridView[col, rowOfInterest].Value = Convert.ChangeType( ob, DataGridView[col,rowOfInterest].ValueType );
catch (Exception enterException)
//do something here


navya said...

Great Article
C# Training in Chennai | C# Online Training | ASP.NET Training in Chennai

C# Training in Chennai | Dot Net Training in Chennai | Dot Net Training in Chennai

Unknown said...

Buenas roy me interesa tu publicación como uso ese código en mi Formulario me guiarías por favor? tengo un Datagridview diseñado y quiero poder pegar rango seleccionados de un excel en mi datagridview

sheela rajesh said...

Awesome informations that you have shared for us.I eagerly waiting for more updates in future.
Hadoop Training in Chennai
Big data training in chennai
Big Data Course in Chennai
JAVA Training in Chennai
Python Training in Chennai
Selenium Training in Chennai
Hadoop training in chennai
Big data training in chennai
big data course in chennai

Tanika Co Valda said...

Big data is a term that describes the large volume of data – both structured and unstructured – that inundates a business on a day-to-day basis. big data projects for students But it’s not the amount of data that’s important. Project Center in Chennai It’s what organizations do with the data that matters. Big data can be analyzed for insights that lead to better decisions and strategic business moves.

Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Corporate TRaining Spring Framework the authors explore the idea of using Java in Big Data platforms.
Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai

The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training