Reputation: 13
I'm creating a Windows Form application, more or less acting as the interface to a SQL db for our users. I want to format the floats to 1 or 2 decimal places when they look at the form, but I also want to have the ability to copy the DataGridView out to excel with the full float if they desire.
For example, if I'm formatting rows to be a percent with 1 decimal place I'll use
DataGridView1.Rows[i].DefaultCellStyle.Format = "P1";
This looks great in the Form, but when I copy the DataGridView to the Clipboard, it copies just 1 decimal place, even if the float from the DataTable I'm using as a source has more decimal places.
I'm having trouble figuring out how to copy the unformatted data to Clipboard. I've even considered making a Copy Button which accesses an invisible DataGridView which is unformatted, but I'd like users to be able to Ctrl-C from the visible, formatted DataGridView.
Any ideas? Even letting me know I'm out of luck would help, as I'll give up on the Ctrl-C functionality and just create a separate Copy function. Thanks.
Upvotes: 1
Views: 1180
Reputation:
It is impossible to allow users to copy something different than what is being displayed (1-decimal values). A workaround to get what you want might be enabling two different "modes" to show the information in the cells: short and long format. And adding a user-friendly way to switch between both modes; for example: pressing "Enter" in a cell. Sample code:
private void dataGridView1_KeyDown(Object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (shortMode)
{
dataGridView1.Rows[curRow].DefaultCellStyle.Format = ""; //Number with all the decimals
shortMode = false;
}
else
{
dataGridView1.Rows[curRow].DefaultCellStyle.Format = "P1"; //Number as percentage with 1 decimal
shortMode = true;
}
}
}
Where shortMode
is a boolean variable declared globally and curRow
is the row you want to change.
Upvotes: 1