欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C# Winform實現(xiàn)表格復(fù)制粘貼效果

 更新時間:2023年07月27日 09:39:32   作者:Csharp 小記  
這篇文章主要為大家學(xué)習(xí)介紹了如何通過C# Winform實現(xiàn)表格復(fù)制粘貼效果,文中的示例代碼講解詳細(xì),具有一定的參考價值,需要的可以了解一下

前言

這是前幾天有粉絲留言咨詢的一個問題,想實現(xiàn)在Winform中對表格數(shù)據(jù)進(jìn)行批量復(fù)制粘貼。我這邊給出的方案就是直接操作數(shù)據(jù)集了,個人認(rèn)為這種方式是最簡單的了。其實我覺得在Winform數(shù)據(jù)表格中,無論是自帶的DataGridView還是其他第三方的Grid控件,大部分情況都可以優(yōu)先考慮通過操作數(shù)據(jù)集來實現(xiàn),而不要優(yōu)先考慮操作UI,即復(fù)雜又困難。

以下代碼可以在Excel與DataGridView中實現(xiàn)相互復(fù)制粘貼,目前只是做了一個效果出來,具體的復(fù)雜情況需要根據(jù)自身需求來做動態(tài)調(diào)整。也可部分參考之前寫的一篇:C#實現(xiàn)表格數(shù)據(jù)轉(zhuǎn)實體

1.先說下實現(xiàn)原理,其實可以觀察Excel的復(fù)制數(shù)據(jù),即把Excel復(fù)制兩行數(shù)據(jù)粘貼到記事本中,會發(fā)現(xiàn)列與列之間是通過制表符來區(qū)分的,而行與行之間就是換行符了。

2.得到這個結(jié)果就可以直接處理粘貼板數(shù)據(jù)了,只要按照上面的格式進(jìn)行字符串拼接或者拆分就行

3.接下來看下實現(xiàn)代碼,首先隨便定義一個實體類用來綁定數(shù)據(jù)源,然后添加幾行測試數(shù)據(jù)

private class Model
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }
        BindingList<Model> BindData=new BindingList<Model>();
        private void Form1_Load(object sender, EventArgs e)
        {
            BindData.Add(new Model { ID=1,Name="張三"});
            BindData.Add(new Model { ID = 2, Name = "李四" });
            BindData.Add(new Model { ID = 3, Name = "王五" });
            gridViewEx1.DataSource = BindData;
        }

4.在KeyDown事件中處理復(fù)制粘貼的數(shù)據(jù),即Ctrl+CCtrl+V

 private void gridViewEx1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.C)
            {
                string data = "";
                var rows = gridViewEx1.SelectedRows;
                foreach (DataGridViewRow row in rows)
                {
                    foreach (DataGridViewColumn column in gridViewEx1.Columns)
                    {
                        data += row.Cells[column.Name] + "\t";
                    }
                    data += "\r";
                }
                Clipboard.SetText(data);
                Layer.Success("復(fù)制成功");
            }
            if (e.Control && e.KeyCode == Keys.V)
            {
                string data = Clipboard.GetText();
                string[] rows = data.Split(new string[] { "\r\n"},StringSplitOptions.RemoveEmptyEntries);
                foreach (string row in rows)
                {
                    string[] columns = row.Split('\t');
                    BindData.Add(new Model { ID = Convert.ToInt32(columns[0]), Name = columns[1] });
                }
                Layer.Success("粘貼成功");
            }
        }

5. 最后來看看效果

到此這篇關(guān)于C# Winform實現(xiàn)表格復(fù)制粘貼效果的文章就介紹到這了,更多相關(guān)C# Winform復(fù)制粘貼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論