Reputation: 1498
I have a DataGridView
that contains an Image
Column and some Text Columns. I have a pretty simple handler that will allow the user to Copy Text or Images out of the cells and Paste Images and Text into them. The Copy/Paste works fine on Text, but the Paste does not work on the Images. (NOTE: If I Paste an image that was placed on the clipboard from another app, like Paint, then it works fine)
If I immediately call a Clipboard.GetImage()
after the Clipboard.SetImage()
it works fine, which leads me to believe that it could be a scope problem or that Clipboard
is grabbing a reference and not the underlying bytes from the image. Do I have to place the raw image bytes in a shared location? I checked the MSDN definition for GetImage to make sure I was doing it correctly.
private void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
if (Clipboard.ContainsImage())
{
Image img = Clipboard.GetImage(); // always returns null
if (cell.ColumnIndex == _imageCol)
cell.Value = img;
}
if (Clipboard.ContainsText())
{
if (cell.ColumnIndex != _imageCol)
cell.Value = Clipboard.GetText(); // always works
}
}
if (e.KeyCode == Keys.C && e.Modifiers == Keys.Control)
{
DataGridViewCell cell = dataGridView1.SelectedCells[0];
if (cell.ColumnIndex == _imageCol)
{
Clipboard.SetImage((Image)cell.Value);
Image img2 = Clipboard.GetImage(); // successfully returns the Image
}
else
Clipboard.SetText((string)cell.Value);
}
}
Upvotes: 3
Views: 1506
Reputation: 942267
What you are not counting on is that DataGridView also implements copy/paste. Using the same shortcut keystrokes as you are using, Ctrl+C and Ctrl+V. So it looks like it works just after you put the image on the clipboard, but then DGV does it as well and overwrites the clipboard content. Unfortunately it doesn't copy images, just text. An empty string for your image column.
You have to tell it that you handled the keystroke:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control) {
// etc...
e.Handled = true;
}
if (e.KeyCode == Keys.C && e.Modifiers == Keys.Control) {
// etc...
e.Handled = true;
}
}
Upvotes: 6