12

DataGridViewにセルが選択されていないようにする方法はありますか?focus()を失っても、少なくとも1つのアクティブセルがあることに気付きました。これを可能にする別のモードはありますか?または他のトリック?

4

7 に答える 7

12

DataGridView.CurrentCellプロパティを使用して、フォーカス長方形をクリアできます。

このプロパティ(DataGridView.CurrentCell)をnullに設定して、フォーカス矩形を一時的に削除できますが、コントロールがフォーカスを受け取り、このプロパティの値がnullの場合、FirstDisplayedCellプロパティの値に自動的に設定されます。

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

于 2008-12-04T15:44:19.553 に答える
7

選択変更イベントで DataGridView.CurrentCell を null に設定する際の問題は、後のイベント (クリックなど) がヒットしないことです。

私にとってうまくいったオプションは、選択色をグリッド色に変更することでした。したがって、選択は表示されません。

RowsDefaultCellStyle.SelectionBackColor = BackgroundColor;
RowsDefaultCellStyle.SelectionForeColor = ForeColor;
于 2012-01-27T21:40:55.777 に答える
7

DataGridView.CurrentCell = null要求された動作を取得しようとすると、うまくいかないことがわかりました。

私が最終的に使用したのは:

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

        dgvMyGrid.SelectionChanged += dgvMyGrid_SelectionChanged;
    }

DataBindingCompleteイベントハンドラーにある必要がありました。

イベントハンドラーをどこにアタッチしてSelectionChangedも目的の動作には影響しませんが、コードスニペットに残しました。これは、選択変更イベントが発生しないように、少なくともデータバインディング後にのみハンドラーをアタッチする方が良いことに気付いたからです。バインドされた各アイテム。

于 2008-12-19T05:18:21.290 に答える
4

この問題の解決策を見つけるのに何時間も費やしました。これを行う:

  1. フォーム プロジェクトを作成する
  2. 「DataGridView1」という名前の DataGridView を追加します。
  3. クラス 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
    

重要なコード行は

    DataGridView1.CurrentRow.Selected = False

幸運を!

于 2009-01-10T18:50:48.400 に答える
3

同様の問題があり、次の方法に従いました。

  1. dataGridView.ClearSelection() によってクリアされた「初期アクティブ セル」。

  2. イベント ハンドラー 'CellMouseClick' イベントで選択をクリア/無視します。

    void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    
    {
    
        DataGridView dgv = sender as DataGridView;
    
        dgv.ClearSelection();
    
    }
    
于 2012-12-27T05:56:58.967 に答える
1

これは古い質問であり、WinForms は取って代わられていることを私は知っています (しかし、いずれにせよ、私たちのショップにまだ長い間ありません)。

または の選択をいじる代わりにCurrentCell、実装が単に行の選択色を変更するだけで、私たちのニーズにより適していることがわかりました。

さらに、フォーカスを失ったときに古い選択セルを追跡する必要がなくなり、フォーカスされていないときにグリッドがリフレッシュされたときに(タイマーなどで)トリッキーな問題に対処する必要がなくなり、フォーカス時に古い選択セルを「復元」できなくなりました返されます。

上で既に投稿した解決策に加えて、コントロールから継承することはできません (したくありませんでした) ためDataGridView、代わりに構成を使用することを選択しました。以下のコードは、機能を実装するために使用されるクラスを示し、その後にそれを使用して動作を 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 );
    }
}

使用法: DataGridViewHideSelection クラスのインスタンスをインスタンス化し、機能が不要になったときに破棄します。

var hideSelection = new DataGridViewHideSelection( myGridView );

// ...

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

または、便利な拡張メソッドAttachHideSelectionBehaviour()を使用して、生活を少し楽にすることもできます。

myDataGrid.AttachHideSelectionBehaviour();

多分それは他の誰かに役立つでしょう。

于 2014-11-15T03:16:57.987 に答える
1

フォーカス/選択をクリアしたい場合はいつでもDataGridView.ClearSelection()を使用します (例: InitializeComponent、 Control.LostFocusForm.Load )。

于 2016-04-21T10:36:55.923 に答える