Re: DataGridView.GetClipboardContent does not call ParseFormattedValue

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



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;
}
.


Quantcast