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)
return;

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

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

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

1 comment:

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