2008-12-04 36 views

Respuesta

10

La propiedad DataGridView.CurrentCell se puede utilizar para borrar el rectángulo de foco.

Puede establecer esta propiedad (DataGridView.CurrentCell) en null para eliminar temporalmente el foco rectángulo, pero cuando el control recibe el foco y el valor de esta propiedad es null , es automáticamente conjunto al valor de la propiedad FirstDisplayedCell .

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

+0

Esto ayuda mucho Gracias –

6

encontré que el DataGridView.CurrentCell = null no funcionó para mí cuando se trata de obtener el comportamiento requerido.

Lo que terminé usando era:

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

     dgvMyGrid.SelectionChanged += dgvMyGrid_SelectionChanged; 
    } 

Tenía que ser en el controlador DataBindingComplete evento.

Cuando adjuntas el controlador de eventos SelectionChanged no afecta el comportamiento deseado, pero lo dejé en el fragmento de código porque noté que para mis necesidades al menos era mejor conectar el controlador después de la unión de datos, para evitar un el evento de selección cambiada se plantea para cada artículo encuadernado.

3

Pasé horas para encontrar la solución a este problema. Haga lo siguiente:

  1. Crear un proyecto Formulario
  2. Añadir un DataGridView con el nombre "DataGridView1"
  3. Agregue el código siguiente a la clase 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 
    

La línea importaint del código es

DataGridView1.CurrentRow.Selected = False 

¡Buena suerte!

6

El problema con la configuración de DataGridView.CurrentCell para anular en el evento de cambio de selección es que los eventos posteriores (como el clic) no se verán afectados.

La opción que funcionó para mí fue cambiar el color de la selección al color de la cuadrícula. La selección, por lo tanto, no será visible.

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

Su solución no hará un DataGridView sin una celda seleccionada. Es solo apariencia ... – nbadaud

3

tuve problema similar y he seguido esta manera:

  1. 'celda activa inicial' despejado por dataGridView.ClearSelection().

  2. Borrar/Ignorar la selección en el controlador de eventos, evento 'CellMouseClick'.

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

Sé que esto es una cuestión de edad y WinForms es sustituida (pero no por mucho tiempo que en la tienda de todos modos), así que esto es todavía relevante para nosotros y sospecho algunos otros también.

En lugar de jugar con la selección o CurrentCell, encontré la implementación simplemente cambiar los colores de selección de fila mucho más adecuados para nuestras necesidades.

Además, ya no tengo que hacer un seguimiento de la antigua celda seleccionada al perder el foco ni tener que lidiar con el problema cuando la red se actualiza cuando no se enfoca (como por un temporizador) y la celda seleccionada no puede ser " restaurado "cuando se devuelve el foco.

Además de las soluciones ya publicadas anteriormente, no pudimos (no queríamos) heredar del control DataGridView y optamos por usar la composición. El siguiente código muestra la clase utilizada para implementar la funcionalidad, seguida de un código sobre cómo usarla para "adjuntar" el comportamiento a un 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); 
    } 
} 

Uso: Para utilizar crear una instancia de la clase DataGridViewHideSelection y disponer de ella cuando no se necesita ninguna funcionalidad-más.

var hideSelection = new DataGridViewHideSelection(myGridView); 

// ... 

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

Como alternativa, puede utilizar el método de extensión conveniente AttachHideSelectionBehaviour() para hacer la vida un poco más fácil.

myDataGrid.AttachHideSelectionBehaviour(); 

Quizás sea útil para otra persona.

Cuestiones relacionadas