Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

DataGridView.GetClipboardContent does not call ParseFormattedValue

15 views
Skip to first unread message

jonpb

unread,
Nov 5, 2009, 2:27:38 PM11/5/09
to
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

unread,
Nov 5, 2009, 7:36:48 PM11/5/09
to
jonpb wrote:
> 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[i].Keys)
cols.Add(k);
cols.Sort();

foreach (int k in cols)
{
tab.AppendFormat("{0}\t", tabs[i][k]);
csv.AppendFormat("{0},", tabs[i][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;
}

0 new messages