Excel And DataGridView Copy/Paste

Here is some code that will allow you to copy/paste text, say from
Excel to a DataGridView or a DataGridView to a DataGridView. It uses
the KeyDown event to catch the ctl+V and ctl+C.

            this.dataGridView1.KeyDown += new
KeyEventHandler(dataGridView1_KeyDown);


        void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.C)
            {
                DataObject d = dataGridView1.GetClipboardContent();
                Clipboard.SetDataObject(d);
                e.Handled = true;
            }
            else if(e.Control && e.KeyCode == Keys.V)
            {
                string s = Clipboard.GetText();
                string[] lines = s.Split('/n');
                int row = dataGridView1.CurrentCell.RowIndex;
                int col = dataGridView1.CurrentCell.ColumnIndex;
                foreach (string line in lines)
                {
                    if (row < dataGridView1.RowCount && line.Length >
0)
                    {
                        string[] cells = line.Split('/t');
                        for (int i = 0; i < cells.GetLength(0); ++i)
                        {
                            if (col + i <
this.dataGridView1.ColumnCount)
                            {
                                dataGridView1[col + i, row].Value =
Convert.ChangeType(cells[i], dataGridView1[col + i, row].ValueType);
                            }
                            else
                            {
                                break;
                            }
                        }
                        row++;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        } 

資料來源:

http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework.adonet/topic62493.aspx

發佈了18 篇原創文章 · 獲贊 0 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章