Thursday, February 15, 2007

DataGrid copy to clipboard

Here's some code I knocked together to copy the contents of a WinForms DataGrid to the clipboard. Probably won't work for all possible data sources but it was good enough for my needs. 

    public void CopyToClipboard()
    {
      StringBuilder builder = new StringBuilder();
      for (int i = 0; i < ts.GridColumnStyles.Count; i++)
      {
        if (i > 0)
          builder.Append("\t");
        builder.Append(ts.GridColumnStyles[i].HeaderText);
      }
      builder.Append(Environment.NewLine);

      CurrencyManager manager = (CurrencyManager)BindingContext[DataSource];

      if (DataSource is DataTable)
      {
        DataTable dt = (DataTable)DataSource;
        foreach(DataRowView r in manager.List)
        {
          for (int i = 0; i < dt.Columns.Count; i++)
          {
            if (i > 0)
              builder.Append("\t");
            builder.Append(r[i].ToString());
          }
          builder.Append(Environment.NewLine);
        }
      }
      else if (DataSource is IList)
      {
        for (int i = 0; i < manager.List.Count; i++)
        {
          object item = manager.List[i];
          Type objectType = item.GetType();
          for (int j = 0; j < ts.GridColumnStyles.Count; j++)
          {
            string colName = ts.GridColumnStyles[j].MappingName;
            PropertyInfo propInfo = objectType.GetProperty(colName);
            object propertyValue = propInfo.GetValue(item, null);
            if (j > 0)
              builder.Append("\t");
            builder.Append(propertyValue.ToString());
          }
          builder.Append(Environment.NewLine);
        }
      }
      else
        throw new NotSupportedException();

      Clipboard.SetDataObject(builder.ToString(), true);
    }

2 comments:

Anonymous said...

Alternatively a quick an dirty solution that will work for any data:

MyDataGrid.SelectAll();
MyDataGrid.Focus();
SendKeys.Send("^(c)");

Anonymous said...

Anonmyous guy, your solution was too good. Except that it doesnot copy headers, but that is okay.