WinForm--DataGridView復制單元格數據


 編寫成右鍵事件:

1  private void 復制ToolStripMenuItem_Click(object sender, EventArgs e) 2  { 3     var cellText = this.dataGridView1.CurrentCell.Value == null ? "" : this.dataGridView1.CurrentCell.Value.ToString(); 4  Clipboard.SetDataObject(cellText); 5  }

使用快捷鍵Ctrl+C:

1  private void dataGridView1_KeyUp(object sender, KeyEventArgs e) 2 { 3     if (e.Modifiers.CompareTo(Keys.Control) == 0 && e.KeyCode == Keys.C) 4  { 5          Clipboard.SetDataObject(this.dataGridView1.CurrentCell.Value.ToString()); 6  } 7 }

使用Clipboard.SetText()向剪貼板寫入字符串時,偶爾會引發System.Runtime.InteropServices.ExternalException異常,異常信息如下:

說明: 由於未經處理的異常,進程終止。 異常信息: System.Runtime.InteropServices.ExternalException 在 System.Windows.Forms.Clipboard.ThrowIfFailed(Int32) 在 System.Windows.Forms.Clipboard.SetDataObject(System.Object, Boolean, Int32, Int32) 在 System.Windows.Forms.Clipboard.SetText(System.String, System.Windows.Forms.TextDataFormat) 在 System.Windows.Forms.Clipboard.SetText(System.String)

由於剪貼板是系統的公共資源,當有多個程序同時訪問時,會引發異常。

解決方案:

可以使用Clipboard.SetDataObject()方法代替Clipboard.SetText(),並設置重試次數與重試間隔:

Clipboard.SetDataObject(text, true, 10, 200);

原文鏈接:https://www.cnblogs.com/weca/p/10789801.html

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM