C#中DataGridView多選技巧有哪些

c#
小樊
82
2024-09-16 09:28:02

在C#中,DataGridView控件默認(rèn)情況下不支持多選

  1. 設(shè)置MultiSelect屬性:將DataGridViewMultiSelect屬性設(shè)置為true。這樣,用戶就可以按住Ctrl或Shift鍵來(lái)選擇多個(gè)單元格或行。

    dataGridView1.MultiSelect = true;
    
  2. 設(shè)置SelectionMode屬性:根據(jù)需要設(shè)置DataGridViewSelectionMode屬性。例如,如果你想允許用戶選擇多行,可以將SelectionMode設(shè)置為FullRowSelect。

    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    
  3. 使用鼠標(biāo)拖動(dòng)選擇:若要啟用用戶通過(guò)拖動(dòng)鼠標(biāo)來(lái)選擇多個(gè)單元格或行的功能,請(qǐng)將DataGridViewMultiSelect屬性設(shè)置為true,并將SelectionMode屬性設(shè)置為CellSelectRowHeaderSelect。

  4. 自定義多選行為:若要實(shí)現(xiàn)更高級(jí)的多選功能,可以處理DataGridViewCellMouseDownCellMouseMoveCellMouseUp事件,以便在用戶拖動(dòng)鼠標(biāo)時(shí)選擇多個(gè)單元格或行。

  5. 獲取選定的單元格和行:要獲取用戶選定的所有單元格和行,可以使用DataGridViewSelectedCellsSelectedRows屬性。例如,以下代碼將輸出選定單元格的數(shù)量和選定行的數(shù)量:

    int selectedCellCount = dataGridView1.SelectedCells.Count;
    int selectedRowCount = dataGridView1.SelectedRows.Count;
    Console.WriteLine($"Selected cells: {selectedCellCount}, Selected rows: {selectedRowCount}");
    
  6. 遍歷選定的單元格和行:要遍歷用戶選定的所有單元格和行,可以使用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的多選功能。

0