DataGridView.GetClipboardContent does not call ParseFormattedValue

  • Thread starter Thread starter jonpb
  • Start date Start date
J

jonpb

Hi,
The default implelmentation of DataGridView.GetClipboardContent does not
call DataGridViewCell.ParseFormattedValue. Does anyone know how to force
it do this, or how to implement GetClipboardContent so that it does. I
am not clear on how, exactly to build a DataObject to put on the Clipboard.

Thanks
 
jonpb said:
The default implelmentation of DataGridView.GetClipboardContent does not
call DataGridViewCell.ParseFormattedValue. Does anyone know how to force
it do this, or how to implement GetClipboardContent so that it does.

For anyone interested, this is my solution. Warning: this code has not
been thoroughly tested, but the general idea is there:

public override DataObject GetClipboardContent()
{
DataObject data = new DataObject();

if (this.SelectedCells.Count == 0) return data;

Dictionary<int, Dictionary<int, string>> tabs = new Dictionary<int,
Dictionary<int, string>>();
Dictionary<int, Dictionary<int, string>> csvs = new Dictionary<int,
Dictionary<int, string>>();
Dictionary<int, string> rt, rc;
StringBuilder tab = new StringBuilder();
StringBuilder csv = new StringBuilder();
foreach (DataGridViewCell cell in this.SelectedCells)
{
if (!tabs.TryGetValue(cell.RowIndex, out rt))
{
rt = new Dictionary<int, string>();
tabs.Add(cell.RowIndex, rt);
rc = new Dictionary<int, string>();
csvs.Add(cell.RowIndex, rc);
}
else
rc = csvs[cell.RowIndex];

rt.Add(cell.ColumnIndex, cell.Value.ToString());
rc.Add(cell.ColumnIndex, cell.Value.ToString());
}

List<int> cols = new List<int>();
List<int> rows = new List<int>();
foreach (int i in tabs.Keys)
rows.Add(i);
rows.Sort();

string s;
foreach (int i in rows)
{
cols.Clear();
foreach (int k in tabs.Keys)
cols.Add(k);
cols.Sort();

foreach (int k in cols)
{
tab.AppendFormat("{0}\t", tabs[k]);
csv.AppendFormat("{0},", tabs[k]);
}

tab.Remove(tab.Length - 1, 1);
tab.AppendLine();
csv.Remove(csv.Length - 1, 1);
csv.AppendLine();
}

data.SetData(DataFormats.CommaSeparatedValue, csv.ToString());
data.SetData(DataFormats.UnicodeText, tab.ToString());
data.SetData(DataFormats.Text, Encoding.ASCII.GetBytes(tab.ToString()));

DataObject html = base.GetClipboardContent();
data.SetData(DataFormats.Html, html.GetData(DataFormats.Html));

return data;
}
 
Back
Top