在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
事件以獲取選定的行。