DataGridViewのコピペで苦戦
DataGridView上でコピペしたい!!と言われました。
で、ためしに「Ctrl+C」「Ctrl+V」してみたけど何もおこらない。
むぅ、しょうがないので、「Ctrl+V」が押されたらイベントを発火する
ユーザーコントロールを作ってみました。
Public Class MyDataGridView Inherits DataGridView ''' <summary> ''' ペースト後のイベント ''' </summary> Public Event AfterPaste As EventHandler Private Sub MyDataGridView_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown 'ペーストの時 If e.Control = True And _ e.KeyCode = Keys.V Then Me.SelectedCells(0).Value = Clipboard.GetText RaiseEvent AfterPaste(sender, e) End If End Sub End Class
で、呼出元で
Private Sub MyDataGridView1_AfterPaste(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyDataGridView1.AfterPaste Dim tmpDgv As MyDataGridView = DirectCast(sender, MyDataGridView) Dim intLastIdx As Integer = tmpDgv.Rows.Count - 1 If String.IsNullOrEmpty(tmpDgv.Rows(intLastIdx).Cells(0).Value) = False Then tmpDgv.Rows.Add() End If End Sub
としてみたのですが・・・
なぜか、新規行が一番下に追加されない。。。
で、ぐぐってみると
http://social.msdn.microsoft.com/Forums/ja-JP/vbgeneralja/thread/f1424a11-08a1-4e3e-88a3-64177f5534c0/
素敵なことが書いてありました。
結局呼び出し元を下のようにして解決Private Sub MyDataGridView1_AfterPaste(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyDataGridView1.AfterPaste Dim tmpDgv As MyDataGridView = DirectCast(sender, MyDataGridView) Dim intLastIdx As Integer = tmpDgv.Rows.Count - 1 tmpDgv.BeginEdit(True) tmpDgv.NotifyCurrentCellDirty(True) tmpDgv.EndEdit() End Sub
これ、でも、CellValidatingが呼び出されていない感じ
1行ずつしかコピペしないなら最後にDataGridView.BeginEdit(True)呼べばいいかなぁ
この点についてはもう少し調べないとな。