VB.NET
dgv1.ClipboardCopyMode = _
DataGridViewClipboardCopyMode.EnableWithoutHeaderText
Clipboard.SetDataObject(dgv1.GetClipboardContent())
C#dgv1.ClipboardCopyMode =
DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
Clipboard.SetDataObject(dgv1.GetClipboardContent());
DataGridViewへデータを張り付ける方法
VB.NET
If dgv1.CurrentCell Is Nothing Then
Return
End If
Dim insertRowIndex As Integer = dgv1.CurrentCell.RowIndex
Dim pasteText As String = Clipboard.GetText()
If String.IsNullOrEmpty(pasteText) Then
Return
End If
pasteText = pasteText.Replace(vbCrLf, vbLf)
pasteText = pasteText.Replace(vbCr, vbLf)
pasteText = pasteText.TrimEnd(New Char() {vbLf})
Dim lines As String() = pasteText.Split(vbLf)
Dim isHeader As Boolean = True
For Each line As String In lines
If isHeader Then
isHeader = False
Else
Dim vals As String() = line.Split(ControlChars.Tab)
If vals.Length - 1 <> dgv1.ColumnCount Then
Throw New ApplicationException("列数に相違があります")
End If
Dim row As DataGridViewRow = dgv1.Rows(insertRowIndex)
row.HeaderCell.Value = vals(0)
Dim i As Integer
For i = 0 To row.Cells.Count - 1
row.Cells(i).Value = vals((i + 1))
Next i
insertRowIndex += 1
End If
Next line
C#if (dgv1.CurrentCell == null)
return;
int insertRowIndex = dgv1.CurrentCell.RowIndex;
string pasteText = Clipboard.GetText();
if (string.IsNullOrEmpty(pasteText))
return;
pasteText = pasteText.Replace("\r\n", "\n");
pasteText = pasteText.Replace('\r', '\n');
pasteText = pasteText.TrimEnd(new char[] { '\n' });
string[] lines = pasteText.Split('\n');
bool isHeader = true;
foreach (string line in lines)
{
if (isHeader)
{
isHeader = false;
continue;
}
string[] vals = line.Split('\t');
if (vals.Length - 1 != dgv1.ColumnCount)
throw new ApplicationException("列数に相違あり");
DataGridViewRow row = dgv1.Rows[insertRowIndex];
row.HeaderCell.Value = vals[0];
for (int i = 0; i < row.Cells.Count; i++)
{
row.Cells[i].Value = vals[i + 1];
}
insertRowIndex++;
}