繁体   English   中英

c# 如何将文本从 label 拖放到 datagridview 中的特定单元格中

[英]c# How do I drag and drop text from label into a specific cell in a datagridview

我正在尝试使用拖放屏幕截图将文本放入特定单元格

这里提供了一个简化的解决方案,请查看 - https://www.codeproject.com/Questions/101532/How-to-apply-drag-drop-cell-content-in-datagridvie

public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();

            //allow drop
            this.dataGridView1.AllowDrop = true;

            //data grid view sample data 
            DataTable dtb = new DataTable();
            dtb.Columns.AddRange(new DataColumn[] { new DataColumn(), new DataColumn(), new DataColumn() });
            
            for (int i = 0; i < 30;)
            {
                dtb.Rows.Add((++i).ToString(), (++i).ToString(), (++i).ToString());    
            }
            dataGridView1.DataSource = dtb;
        }

        private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                dataGridView1.DoDragDrop(dataGridView1[e.ColumnIndex,e.RowIndex].FormattedValue, DragDropEffects.Copy);
            }
        }

        private void dataGridView1_DragDrop(object sender, DragEventArgs e)
        {
            string cellvalue=e.Data.GetData(typeof(string)) as string;
            Point cursorLocation=this.PointToClient(new Point(e.X,e.Y));

            System.Windows.Forms.DataGridView.HitTestInfo hittest= dataGridView1.HitTest(cursorLocation.X,cursorLocation.Y);
            if (hittest.ColumnIndex != -1
                && hittest.RowIndex != -1)
                dataGridView1[hittest.ColumnIndex, hittest.RowIndex].Value = cellvalue;
        }

        private void dataGridView1_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM