在C#中,要实现自定义的DataGridView多选功能,你需要创建一个自定义的DataGridView控件,并重写其行为
SelectedRowsChanged
,以便在选择的行发生变化时通知其他控件。以下是一个简单的示例:
using System;
using System.Windows.Forms;
public partial class CustomDataGridView : UserControl
{
public event EventHandler SelectedRowsChanged;
public CustomDataGridView()
{
InitializeComponent();
dataGridView1.CellMouseDown += DataGridView1_CellMouseDown;
dataGridView1.KeyDown += DataGridView1_KeyDown;
}
private void DataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Left && e.RowIndex >= 0)
{
if (ModifierKeys == Keys.Shift)
{
// 使用Shift键进行多选
int lastSelectedRowIndex = dataGridView1.CurrentCell.RowIndex;
int currentRowIndex = e.RowIndex;
for (int i = Math.Min(lastSelectedRowIndex, currentRowIndex); i <= Math.Max(lastSelectedRowIndex, currentRowIndex); i++)
{
dataGridView1.Rows[i].Selected = true;
}
}
else if (ModifierKeys == Keys.Control)
{
// 使用Ctrl键进行多选
dataGridView1.Rows[e.RowIndex].Selected = !dataGridView1.Rows[e.RowIndex].Selected;
}
else
{
// 正常单选
dataGridView1.ClearSelection();
dataGridView1.Rows[e.RowIndex].Selected = true;
}
SelectedRowsChanged?.Invoke(this, EventArgs.Empty);
}
}
private void DataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
{
int selectedRowIndex = dataGridView1.CurrentCell.RowIndex;
int newRowIndex = e.KeyCode == Keys.Up ? selectedRowIndex - 1 : selectedRowIndex + 1;
if (newRowIndex >= 0 && newRowIndex< dataGridView1.Rows.Count)
{
if (ModifierKeys == Keys.Shift)
{
// 使用Shift键进行多选
for (int i = Math.Min(selectedRowIndex, newRowIndex); i <= Math.Max(selectedRowIndex, newRowIndex); i++)
{
dataGridView1.Rows[i].Selected = true;
}
}
else if (ModifierKeys == Keys.Control)
{
// 使用Ctrl键进行多选
dataGridView1.Rows[newRowIndex].Selected = !dataGridView1.Rows[newRowIndex].Selected;
}
else
{
// 正常单选
dataGridView1.ClearSelection();
dataGridView1.Rows[newRowIndex].Selected = true;
}
SelectedRowsChanged?.Invoke(this, EventArgs.Empty);
}
}
}
}
现在,你可以在你的主窗体或其他控件中使用这个自定义的DataGridView,并处理SelectedRowsChanged
事件以获取选定的行。