views:

51

answers:

1

I have a program that displays numbers in a System.Windows.Forms.DataGridView. I'm formatting those numbers according to the user's regional settings, which causes problems when I try to copy and paste said numbers into Excel. For example, 123 456 789,00 is the proper localized format in Finnish, but Excel interprets this as a string, not as a number. Is there a way to either make Excel understand thousand separators in numbers or to use a different number format for the clipboard?

A: 

You can create your own DGV derived class and override the GetClipboardContent() method. Which allows you to format the string in a way that's compatible with Excel. Something like this:

using System;
using System.Windows.Forms;

class MyDGV : DataGridView {
    public override DataObject GetClipboardContent() {
        if (this.SelectedCells.Count == 1 && this.SelectedCells[0].ColumnIndex == 1) {
            string value = string.Format("{0:N2}", this.SelectedCells[0].Value);
            return new DataObject(DataFormats.Text, value);
        }
        return base.GetClipboardContent();
    }
}

Untested.

Hans Passant