Created
November 21, 2017 16:06
-
-
Save Lycheejam/b018d42fe65402b3c129a49b3641be14 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void dgv_KeyDown(object sender, KeyEventArgs e) | |
{ | |
if (e.KeyCode == Keys.V && e.Control == true) | |
{ | |
try | |
{ | |
//クリップボードからテキスト取得 | |
string temp = Clipboard.GetText(); | |
//改行コードで文字列分割(1レコード単位に) | |
string[] lines = temp.Split(new string[] { "\r\n" }, StringSplitOptions.None); | |
string[] spLine; | |
//1行目を項目行と仮定 | |
spLine = lines[0].Split(new char[] { ',', '\t' }, StringSplitOptions.None); | |
dgv.ColumnCount = spLine.Length; //カラム追加 | |
for (int i = 0; i < spLine.Length; i++) | |
{ | |
//replaceでやろうと10分ぐらい悩んだけどすでに分割されてるからtrimでok | |
dgv.Columns[i].HeaderText = spLine[i].Trim('"'); | |
} | |
//datagridviewのレコード配列(全レコードを格納) | |
DataGridViewRow[] rows = new DataGridViewRow[lines.Length - 1]; | |
//項目行を抜いてスタート | |
for (int i = 1; i < lines.Length; i++) | |
{ | |
//空白の要素はちゃんと空白が入ってくれるから毎回の初期化はいらない | |
spLine = lines[i].Split(new char[] { ',' , '\t' }, StringSplitOptions.None); | |
for (int j = 0; j < spLine.Length; j++) | |
{ | |
//ダブルクオートを除去 | |
spLine[j] = spLine[j].Trim('"'); | |
} | |
//1レコードを格納 | |
DataGridViewRow row = new DataGridViewRow(); | |
row.CreateCells(dgv); | |
row.SetValues(spLine); | |
//レコードを全レコード配列(ちょっと日本語おかしい)に格納 | |
rows[i -1] = row; | |
} | |
//配列を配列の大きさの範囲にぶち込む | |
dgv.Rows.AddRange(rows); | |
} | |
catch (Exception ex) | |
{ | |
MessageBox.Show(ex.Message); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment