Datagridgridview拖放事件
本文关键字:事件 拖放 Datagridgridview | 更新日期: 2023-09-27 18:20:17
我正在尝试编写一个拖放函数,但遇到了一点困难。
我的问题如下:
1.)根据所附代码,Load_Load事件是应该首先调用,还是它在哪个序列中重要(正如你所看到的,它是这组代码中调用的最后一个事件)。
2.)然而,当我在网格二上单击单元格或列标题时,拖放事件是有效的:mscorlib.dll中发生了类型为"System.ArgumentOutOfRangeException"的未处理异常。我如何修复此项?
3.)在数据网格2中,单元0和1被编号为单元0和单元1。当我将鼠标悬停在两个单元格上时,单元格0为0-1,单元格1为1-2,其余单元格标题没有编号或没有工具提示。这是怎么解决的?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Suite_Estimation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(System.String)))
{
Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));
dataGridView1.Rows[dataGridView1.HitTest(clientPoint.X, clientPoint.Y).RowIndex].Cells[dataGridView1.HitTest(clientPoint.X, clientPoint.Y).ColumnIndex].Value = (System.String)e.Data.GetData(typeof(System.String));
}
}
private void dataGridView1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(System.String)))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void dataGridView2_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
dataGridView2.DoDragDrop(dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), DragDropEffects.Copy);
}
private void Form1_Load(object sender, EventArgs e)
{
DataGridViewRow dr = new DataGridViewRow();
dataGridView2.Rows.Add(5);
dataGridView2.Rows[0].Cells[0].Value = "00000000";
dataGridView2.Rows[1].Cells[0].Value = "11111111";
dataGridView2.Rows[2].Cells[0].Value = "22222222";
dataGridView2.Rows[3].Cells[0].Value = "33333333";
dataGridView2.Rows[4].Cells[0].Value = "44444444";
dataGridView2.Rows[0].HeaderCell.Value = "0 - 1";
dataGridView2.Rows[1].HeaderCell.Value = "1 - 2";
}
}
}
试试这个
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex > -1 && e.ColumnIndex > -1)
dataGridView1.DoDragDrop(
dataGridView1.Rows[e.RowIndex]
.Cells[e.ColumnIndex]
.Value.ToString(),
DragDropEffects.Copy);
}
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(System.String)))
{
Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));
int rowIndex = dataGridView1.HitTest(clientPoint.X, clientPoint.Y).RowIndex;
int colIndex = dataGridView1.HitTest(clientPoint.X, clientPoint.Y).ColumnIndex;
if (rowIndex > -1 && colIndex > -1)
dataGridView1.Rows[rowIndex].Cells[colIndex].Value =
(System.String)e.Data.GetData(typeof(System.String));
}
}