2008-12-04 32 views
11

Có cách nào để tạo một DataGridView không có ô nào được chọn không? Tôi nhận thấy ngay cả khi nó mất tiêu điểm() nó có ít nhất một ô hiện hoạt. Có chế độ nào khác cho phép điều này không? hoặc một số thủ thuật khác?WinForms - DataGridView - không có ô nào được chọn

Trả lời

10

Thuộc tính DataGridView.CurrentCell có thể được sử dụng để xóa hình chữ nhật tiêu điểm.

Bạn có thể đặt khách sạn này (DataGridView.CurrentCell) null để tạm thời loại bỏ các tập trung hình chữ nhật, nhưng khi kiểm soát nhận tập trung và giá trị của tài sản này là null, nó là tự động bộ với giá trị của thuộc tính FirstDisplayedCell.

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.currentcell.aspx

+0

Điều này giúp ích rất nhiều Cảm ơn –

6

tôi thấy rằng các DataGridView.CurrentCell = null không làm việc cho tôi khi cố gắng để có được những hành vi được yêu cầu.

gì tôi đã kết thúc sử dụng là:

private void dgvMyGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) 
    { 
     if (dgvMyGrid.SelectedRows.Count > 0) 
     { 
      dgvMyGrid.SelectedRows[0].Selected = false; 
     } 

     dgvMyGrid.SelectionChanged += dgvMyGrid_SelectionChanged; 
    } 

Nó cần thiết để được trong xử lý DataBindingComplete sự kiện.

Trường hợp bạn đính kèm bộ xử lý sự kiện SelectionChanged không ảnh hưởng đến hành vi mong muốn nhưng tôi đã để nó trong đoạn mã vì tôi nhận thấy nhu cầu của mình ít nhất là chỉ nên đính kèm trình xử lý sau khi dữ liệu, để tránh lựa chọn thay đổi sự kiện được nâng lên cho mỗi mục bị ràng buộc.

3

Tôi đã dành hàng giờ để tìm giải pháp cho vấn đề này. Làm điều này:

  1. Tạo một dự án Mẫu
  2. Thêm một DataGridView với cái tên "DataGridView1"
  3. Thêm mã sau đây để lớp học của bạn Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
    
    Dim dgvRow(17) As DataGridViewRow 
    Dim i As Integer 
    For i = 0 To dgvRow.Length - 1 
        dgvRow(i) = New DataGridViewRow() 
        dgvRow(i).Height = 16 
        dgvRow(i).Selected = False 
        dgvRow(i).ReadOnly = True 
        DataGridView1.Rows.Add(dgvRow(i)) 
        DataGridView1.CurrentRow.Selected = False 
    Next 
    End Sub 
    

Dòng importaint của mã là

DataGridView1.CurrentRow.Selected = False 

Chúc bạn may mắn!

6

Sự cố khi đặt DataGridView.CurrentCell thành null trên sự kiện thay đổi lựa chọn là các sự kiện sau này (như nhấp chuột) sẽ không bị trúng.

Tùy chọn làm việc cho tôi là thay đổi màu lựa chọn thành màu lưới. Do đó, lựa chọn sẽ không hiển thị.

RowsDefaultCellStyle.SelectionBackColor = BackgroundColor; 
RowsDefaultCellStyle.SelectionForeColor = ForeColor; 
+0

Giải pháp của bạn sẽ không tạo ra một DataGridView mà không chọn ô nào. Nó chỉ xuất hiện ... – nbadaud

3

Tôi có vấn đề tương tự và tôi đi theo cách này:

  1. 'tế bào hoạt động ban đầu' xóa bởi dataGridView.ClearSelection().

  2. Xóa/Bỏ qua lựa chọn trong trình xử lý sự kiện, Sự kiện 'CellMouseClick'.

    void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) 
    
    { 
    
        DataGridView dgv = sender as DataGridView; 
    
        dgv.ClearSelection(); 
    
    } 
    
1

Tôi biết đây là một câu hỏi cũ và WinForms được thay thế (nhưng không phải một thời gian dài trong khi vẫn còn trong cửa hàng của chúng tôi anyway), vì vậy đây là vẫn còn có liên quan đến chúng tôi và tôi nghi ngờ một vài người khác quá.

Thay vì không có lựa chọn hoặc CurrentCell, tôi nhận thấy việc triển khai chỉ đơn giản là thay đổi màu lựa chọn hàng phù hợp hơn cho nhu cầu của chúng tôi. Ngoài ra, tôi không còn phải theo dõi ô đã chọn cũ khi mất tiêu điểm cũng như không giải quyết được vấn đề phức tạp khi lưới được làm mới khi không lấy nét (chẳng hạn như hẹn giờ) và ô đã chọn cũ không thể là "#: khôi phục "khi tiêu điểm được trả về.

Ngoài các giải pháp đã được đăng ở trên, chúng tôi không thể (không muốn) thừa kế từ điều khiển DataGridView và thay vào đó đã chọn sử dụng sáng tác. Đoạn mã dưới đây cho thấy lớp được sử dụng để thực hiện chức năng, theo sau là mã về cách sử dụng nó để "đính kèm" hành vi đó vào một DataGridView.

/// <summary> 
/// Responsible for hiding the selection of a DataGridView row when the control loses focus. 
/// </summary> 
public class DataGridViewHideSelection : IDisposable 
{ 
    private readonly DataGridView _dataGridView; 

    private Color _alternatingRowSelectionBackColor = Color.Empty; 
    private Color _alternatingRowSelectionForeColor = Color.Empty; 
    private Color _rowSelectionBackColor = Color.Empty; 
    private Color _rowSelectionForeColor = Color.Empty; 

    /// <summary> 
    /// Initializes a new instance of the <see cref="DataGridViewHideSelection"/> class. 
    /// </summary> 
    /// <param name="dataGridView">The data grid view.</param> 
    public DataGridViewHideSelection(DataGridView dataGridView) 
    { 
     if (dataGridView == null) 
      throw new ArgumentNullException("dataGridView"); 

     _dataGridView = dataGridView; 
     _dataGridView.Enter += DataGridView_Enter; 
     _dataGridView.Leave += DataGridView_Leave; 
    } 

    /// <summary> 
    /// Handles the Enter event of the DataGridView control. 
    /// </summary> 
    /// <param name="sender">The source of the event.</param> 
    /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> 
    private void DataGridView_Enter(object sender, EventArgs e) 
    { 
     // Restore original colour 
     if (_rowSelectionBackColor != Color.Empty) 
      _dataGridView.RowsDefaultCellStyle.SelectionBackColor = _rowSelectionBackColor; 

     if (_rowSelectionForeColor != Color.Empty) 
      _dataGridView.RowsDefaultCellStyle.SelectionForeColor = _rowSelectionForeColor; 

     if (_alternatingRowSelectionBackColor != Color.Empty) 
      _dataGridView.AlternatingRowsDefaultCellStyle.SelectionBackColor = _alternatingRowSelectionBackColor; 

     if (_alternatingRowSelectionForeColor != Color.Empty) 
      _dataGridView.AlternatingRowsDefaultCellStyle.SelectionForeColor = _alternatingRowSelectionForeColor; 
    } 

    /// <summary> 
    /// Handles the Leave event of the DataGridView control. 
    /// </summary> 
    /// <param name="sender">The source of the event.</param> 
    /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> 
    private void DataGridView_Leave(object sender, EventArgs e) 
    { 
     // Backup original colour 
     _rowSelectionBackColor = _dataGridView.RowsDefaultCellStyle.SelectionBackColor; 
     _rowSelectionForeColor = _dataGridView.RowsDefaultCellStyle.SelectionForeColor; 
     _alternatingRowSelectionBackColor = _dataGridView.RowsDefaultCellStyle.SelectionBackColor; 
     _alternatingRowSelectionForeColor = _dataGridView.RowsDefaultCellStyle.SelectionForeColor; 

     // Change to "blend" in 
     _dataGridView.RowsDefaultCellStyle.SelectionBackColor = _dataGridView.RowsDefaultCellStyle.BackColor; 
     _dataGridView.RowsDefaultCellStyle.SelectionForeColor = _dataGridView.RowsDefaultCellStyle.ForeColor; 
     _dataGridView.AlternatingRowsDefaultCellStyle.SelectionBackColor = _dataGridView.AlternatingRowsDefaultCellStyle.BackColor; 
     _dataGridView.AlternatingRowsDefaultCellStyle.SelectionForeColor = _dataGridView.AlternatingRowsDefaultCellStyle.ForeColor; 
    } 

    #region IDisposable implementation (for root base class) 

    private bool _disposed; 

    /// <summary> 
    /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. 
    /// </summary> 
    /// <remarks> 
    /// Called by consumers. 
    /// </remarks> 
    public void Dispose() 
    { 
     Dispose(true); 
     GC.SuppressFinalize(this); 
    } 

    /// <summary> 
    /// Disposes this instance, with an indication whether it is called from managed code or the GC's finalization of this instance. 
    /// </summary> 
    /// <remarks> 
    /// Overridden by inheritors. 
    /// </remarks> 
    /// <param name="disposingFromManagedCode">if set to <c>true</c> disposing from managed code.</param> 
    protected virtual void Dispose(Boolean disposingFromManagedCode) 
    { 
     if (_disposed) 
      return; 

     // Clean up managed resources here 
     if (disposingFromManagedCode) 
     { 
      if (_dataGridView != null) 
      { 
       _dataGridView.Enter -= DataGridView_Enter; 
       _dataGridView.Leave -= DataGridView_Leave; 
      } 
     } 

     // Clean up any unmanaged resources here 

     // Signal disposal has been done. 
     _disposed = true; 
    } 

    /// <summary> 
    /// Finalize an instance of the <see cref="DataGridViewHideSelection"/> class. 
    /// </summary> 
    ~DataGridViewHideSelection() 
    { 
     Dispose(false); 
    } 

    #endregion 
} 


/// <summary> 
/// Extends data grid view capabilities with additional extension methods. 
/// </summary> 
public static class DataGridViewExtensions 
{ 
    /// <summary> 
    /// Attaches the hide selection behaviour to the specified DataGridView instance. 
    /// </summary> 
    /// <param name="dataGridView">The data grid view.</param> 
    /// <returns></returns> 
    /// <exception cref="System.ArgumentNullException">dataGridView</exception> 
    public static DataGridViewHideSelection AttachHideSelectionBehaviour(this DataGridView dataGridView) 
    { 
     if (dataGridView == null) 
      throw new ArgumentNullException("dataGridView"); 

     return new DataGridViewHideSelection(dataGridView); 
    } 
} 

Cách sử dụng: Để sử dụng nhanh chóng một thể hiện của lớp DataGridViewHideSelection và vứt bỏ nó khi bạn không cần chức năng bất kỳ-hơn.

var hideSelection = new DataGridViewHideSelection(myGridView); 

// ... 

/// When no longer needed 
hideSelection.Dispose(); 

Hoặc, bạn có thể sử dụng phương pháp tiện ích mở rộng thuận tiện AttachHideSelectionBehaviour() để làm cho cuộc sống dễ dàng hơn một chút.

myDataGrid.AttachHideSelectionBehaviour(); 

Có thể điều đó hữu ích cho người khác.

Các vấn đề liên quan