在C#中,DataGridView
控件默認(rèn)情況下不支持多選
設(shè)置MultiSelect
屬性:將DataGridView
的MultiSelect
屬性設(shè)置為true
。這樣,用戶就可以按住Ctrl或Shift鍵來(lái)選擇多個(gè)單元格或行。
dataGridView1.MultiSelect = true;
設(shè)置SelectionMode
屬性:根據(jù)需要設(shè)置DataGridView
的SelectionMode
屬性。例如,如果你想允許用戶選擇多行,可以將SelectionMode
設(shè)置為FullRowSelect
。
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
使用鼠標(biāo)拖動(dòng)選擇:若要啟用用戶通過(guò)拖動(dòng)鼠標(biāo)來(lái)選擇多個(gè)單元格或行的功能,請(qǐng)將DataGridView
的MultiSelect
屬性設(shè)置為true
,并將SelectionMode
屬性設(shè)置為CellSelect
或RowHeaderSelect
。
自定義多選行為:若要實(shí)現(xiàn)更高級(jí)的多選功能,可以處理DataGridView
的CellMouseDown
、CellMouseMove
和CellMouseUp
事件,以便在用戶拖動(dòng)鼠標(biāo)時(shí)選擇多個(gè)單元格或行。
獲取選定的單元格和行:要獲取用戶選定的所有單元格和行,可以使用DataGridView
的SelectedCells
和SelectedRows
屬性。例如,以下代碼將輸出選定單元格的數(shù)量和選定行的數(shù)量:
int selectedCellCount = dataGridView1.SelectedCells.Count;
int selectedRowCount = dataGridView1.SelectedRows.Count;
Console.WriteLine($"Selected cells: {selectedCellCount}, Selected rows: {selectedRowCount}");
遍歷選定的單元格和行:要遍歷用戶選定的所有單元格和行,可以使用foreach
循環(huán)。例如,以下代碼將輸出選定單元格的值和選定行的索引:
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
Console.WriteLine($"Cell value: {cell.Value}");
}
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
Console.WriteLine($"Row index: {row.Index}");
}
通過(guò)以上方法,你可以在C#中實(shí)現(xiàn)DataGridView
的多選功能。