excel 内容粘贴到datagridview

 

        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.Columns.Add("FIELD_NAME", "字段名");
            dataGridView1.Columns.Add("FIELD_DESC", "字段描述");
            dataGridView1.Columns.Add("FIELD_TYPE", "字段类型");
            dataGridView1.Columns.Add("FIELD_LEN", "长度");
        }

        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string pasteText = Clipboard.GetText();
                if (string.IsNullOrEmpty(pasteText))
                {
                    return;
                }

                string[] lines = pasteText.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);               
                foreach (string line in lines)
                {                   
                    string[] strs = line.Split(new char[] { '\t' });                                       
                    dataGridView1.Rows.Add(strs);
                }
            }
            catch
            {
                //
            }           
        }


              
            //DataTable dt = new DataTable();     
            //dt.Columns.Add("FIELD_NAME", typeof(string));
            //dt.Columns.Add("FIELD_DESC", typeof(string));
            //dt.Columns.Add("FIELD_TYPE", typeof(string));
            //dt.Columns.Add("FIELD_LEN", typeof(Int32));
            //dataGridView1.DataSource = dt;
            //try
            //{
            //    string pasteText = Clipboard.GetText();
            //    if (string.IsNullOrEmpty(pasteText))
            //    {
            //        return;
            //    }

            //    string[] lines = pasteText.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
            //    foreach (string line in lines)
            //    {
            //        string[] strs = line.Split(new char[] { '\t' });
            //        dt.Rows.Add(strs);
            //        //DataGridView控件被数据绑定时,无法以编程方式向DataGridView的行集合中添加行
            //        //dataGridView1.Rows.Add(strs );
            //    }
            //    dt.AcceptChanges();
            //}
            //catch
            //{
            //    //
            //}

 

posted @ 2010-10-12 12:34  abenz  阅读(883)  评论(1编辑  收藏  举报