datagridview像excel一样实现下拉填充

背景:

之前收到需要在datagridview中设计统一填充功能的需求,类似excel的下拉填充,开始没想到怎么实现,就用了另一种途径(选中多行,编辑,enter,统一填充),但是因为操作上不为人所知,所以被称为“反人类”,哈哈哈

现在算是大概实现了,就是不知道方法是不是最好的,

设计思路:

1. datagridview在MouseMove事件中,检查鼠标是否位于选中单元格的右下角,如果是,则做填充标记,并改变鼠标为十字状态。

2. 在MouseDown事件中,如果是填充标记,则保持鼠标十字状态

3. 在MouseUp事件中,如果是填充标记,则填充所选单元格

代码:

 1         bool isFill = false;
 2         /// <summary>
 3         /// 鼠标移动时,检查是否在选中单元格右下角,若是,则变为十字,标记状态
 4         /// </summary>
 5         /// <param name="sender"></param>
 6         /// <param name="e"></param>
 7         private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
 8         {
 9             if (dataGridView1.SelectedCells.Count == 1)
10             {
11                 int rowIndex = dataGridView1.SelectedCells[0].RowIndex;
12                 int columnIndex = dataGridView1.SelectedCells[0].ColumnIndex;
13                 //返回单元格相对于datagridview的Rectangle
14                 Rectangle r = dataGridView1.GetCellDisplayRectangle(columnIndex, rowIndex, false);
15                 int x = r.X + r.Width;//单元格右下角相对于datagridview的坐标x
16                 int y = r.Y + r.Height;//单元格右下角相对于datagridview的坐标y
17                 if (Math.Abs(e.X - x) < r.Width / 10 && Math.Abs(e.Y - y) < r.Height / 5)
18                 {
19                     this.Cursor = System.Windows.Forms.Cursors.Cross;
20                     isFill = true;
21                 }
22                 else
23                 {
24                     isFill = false;
25                 }
26             }
27         }
28         /// <summary>
29         /// 若是十字填充,则鼠标弹起时,填充数据
30         /// </summary>
31         /// <param name="sender"></param>
32         /// <param name="e"></param>
33         private void dataGridView1_MouseUp(object sender, MouseEventArgs e)
34         {
35             if (isFill )
36             {
37                 isFill = false;
38                 if (dataGridView1.SelectedCells.Count > 1)
39                 {
40                     int count = dataGridView1.SelectedCells.Count;
41                     for (int i = 0; i < count-1; i++)
42                     {
43                         dataGridView1.SelectedCells[i].Value = dataGridView1.SelectedCells[count-1].Value;
44                     }
45                 }
46             }
47                 
48                     
49         }
50         /// <summary>
51         /// 若是十字填充,则鼠标按下时,保持状态
52         /// </summary>
53         /// <param name="sender"></param>
54         /// <param name="e"></param>
55         private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
56         {
57             if (isFill)
58             {
59                 this.Cursor = System.Windows.Forms.Cursors.Cross;
60             }
61         }

猜你喜欢

转载自www.cnblogs.com/zdyzmy/p/12128910.html