using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace gridview
{
public partial class Form1 : Form
{
bool buttonIsPressed = false;
int rowIndex, columnIndex;
public Form1()
{
InitializeComponent();
completeDataGridview();
}
//this function only creates a filled DataGridView
private void completeDataGridview()
{
dataGridView1.RowCount = 3;
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
dataGridView1.Rows[x].Cells[y].Value = ((char)(97 + y + 3 * x)).ToString();
}
}
// this part is stolen from http://stackoverflow.com/questions/7412098/fit-datagridview-size-to-rows-and-columnss-total-size
int height = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
height += row.Height;
}
height += dataGridView1.ColumnHeadersHeight;
int width = 0;
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
width += col.Width;
}
width += dataGridView1.RowHeadersWidth;
dataGridView1.ClientSize = new Size(width + 2, height);
}
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
buttonIsPressed = true;
rowIndex = e.RowIndex;
columnIndex = e.ColumnIndex;
}
private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
if (buttonIsPressed)
{
int startingRow = 0;
if (rowIndex > e.RowIndex)
startingRow = e.RowIndex;
else
startingRow = rowIndex;
//at first we have to deselect every cell
deselectEveryCell();
//then reselect the old ones
int amountOfRows = Math.Abs(rowIndex - e.RowIndex) + 1;
for (int x = 0; x < amountOfRows; x++)
{
dataGridView1.Rows[startingRow + x].Cells[columnIndex].Selected = true;
}
}
buttonIsPressed = false;
}
private void deselectEveryCell()
{
for (int x = 0; x < dataGridView1.RowCount; x++)
{
for (int y = 0; y < dataGridView1.ColumnCount; y++)
{
dataGridView1.Rows[x].Cells[y].Selected = false;
}
}
}
private void dataGridView1_MouseLeave(object sender, EventArgs e)
{
if (buttonIsPressed)
deselectEveryCell();
}
}
}
这是您需要的代码。功能completeDataGridview()
并不重要。
您需要 3 个事件。CellMouseDown
,CellMouseUp
和MouseLeave
.
在CellMouseDown
我们获取初始选定单元格的信息并将其保存在 rowindex 和 columnindex 中。并且 buttonPressed 设置为 true (这在以后可能会有所帮助)。
如果在鼠标指针指向单元格时释放鼠标按钮,CellMouseUp
则触发事件。我们首先检查哪个单元格更靠近 DGV 的顶部(开始处的单元格或当前单元格)。然后取消选择每个单元格。然后我们检查我们选择的单元格的数量(存储在 中amountOfRows
)。然后我们再次选择“正确”的单元格。
该事件MouseLeave
也可能很重要。否则,用户可以通过开始选择一个单元格并将鼠标拖出 DGV 来“滥用”您的功能。如果没有该功能,他将能够选择多个列。
如果您仍有任何问题,请不要犹豫。