簡體   English   中英

如何取消選擇DataGridView控件中的所有選定行?

[英]How to deselect all selected rows in a DataGridView control?

當用戶單擊控件的空白(非行)部分時,我想取消選擇DataGridView控件中的所有選定行。
我怎樣才能做到這一點?

要取消選擇DataGridView所有行和單元格,可以使用ClearSelection方法

myDataGridView.ClearSelection()

如果您不希望第一行/單元格顯示為已選中,則可以CurrentCell屬性設置為Nothing / null ,這將暫時隱藏焦點矩形,直到控件再次獲得焦點:

myDataGridView.CurrentCell = Nothing

要確定用戶何時單擊DataGridView的空白部分,您將不得不處理其MouseUp事件。 在那種情況下,您可以HitTest點擊位置並觀察此點以指示HitTestInfo.Nowhere 例如:

Private Sub myDataGridView_MouseUp(ByVal sender as Object, ByVal e as System.Windows.Forms.MouseEventArgs)
    ''# See if the left mouse button was clicked
    If e.Button = MouseButtons.Left Then
        ''# Check the HitTest information for this click location
        If myDataGridView.HitTest(e.X, e.Y) = DataGridView.HitTestInfo.Nowhere Then
            myDataGridView.ClearSelection()
            myDataGridView.CurrentCell = Nothing
        End If
    End If
End Sub

當然,您也可以將現有DataGridView控件子類化,以將所有這些功能組合到一個自定義控件中。 您需要覆蓋其OnMouseUp方法,類似於上面顯示的方式。 我還想提供一個公共的DeselectAll方法,以方便調用ClearSelection方法並將CurrentCell屬性設置為Nothing

(代碼示例在VB.NET中都是任意的,因為如果這不是您的本地方言,問題不會指定語言道歉。)

謝謝Cody繼承了c#的ref:

if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            DataGridView.HitTestInfo hit = dgv_track.HitTest(e.X, e.Y);
            if (hit.Type == DataGridViewHitTestType.None)
            {
                dgv_track.ClearSelection();
                dgv_track.CurrentCell = null;
            }
        }

我發現為什么我的第一行是默認選擇,並找出默認情況下如何不選擇它。

默認情況下,我的datagridview是我的Windows窗體上第一個制表位的對象。 使標簽首先停在另一個對象上(可能會禁用數據網格的tabstop)將禁用選擇第一行

dgv.CurrentCell = null;

當用戶點擊dgv的空白部分時。

我遇到了同樣的問題,並找到了解決方案(不完全是我自己,但有互聯網)

Color blue  = ColorTranslator.FromHtml("#CCFFFF");
Color red = ColorTranslator.FromHtml("#FFCCFF");
Color letters = Color.Black;

foreach (DataGridViewRow r in datagridIncome.Rows)
{
    if (r.Cells[5].Value.ToString().Contains("1")) { 
        r.DefaultCellStyle.BackColor = blue;
        r.DefaultCellStyle.SelectionBackColor = blue;
        r.DefaultCellStyle.SelectionForeColor = letters;
    }
    else { 
        r.DefaultCellStyle.BackColor = red;
        r.DefaultCellStyle.SelectionBackColor = red;
        r.DefaultCellStyle.SelectionForeColor = letters;
    }
}

這是一個小技巧,選擇行的唯一方法是第一列(不是列[0],而是一列)。 單擊另一行時,您將不再看到藍色選擇,只有箭頭指示選擇了哪一行。 如您所知,我在gridview中使用rowSelection。

在VB.net中使用Sub:

    Private Sub dgv_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgv.MouseUp
    ' deselezionare se click su vuoto
    If e.Button = MouseButtons.Left Then
        ' Check the HitTest information for this click location
        If Equals(dgv.HitTest(e.X, e.Y), DataGridView.HitTestInfo.Nowhere) Then
            dgv.ClearSelection()
            dgv.CurrentCell = Nothing
        End If
    End If
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM