DataGridView 一些設置

幾年沒有用WinForm

1, 自動隨窗口調整大小
(1) 屬性-->配置-->Anchor

2, Grid的欄位寬度根據單元格的內容自動調整
(1) 屬性-->配置-->AutoSizeColumnsMode=Fill
(2) 屬性窗口,按【編輯資料行...】。屬性-->配置-->AutoSizeMode=AllCells
方法2:程式控制
(1) 事件=DataBindingComplete
(2) 對每一列設置(每一列當作控件)
    Private Sub gvDetail_DataBindingComplete(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles gvDetail.DataBindingComplete
        Me.gv_Row_txt_Name.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
    End Sub

3, 加載Grid
(1) grid1.AutoGenerateColumns = False
    grid1.DataSource = dt

4, 清空Grid
(1) grd.DataSource = Nothing
    grd.Rows.Clear()

5, 光標切換到行時,選中該行
(1) 事件=RowEnter
Private Sub gvDetail_RowEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gvDetail.RowEnter
(2) Dim currRow As DataGridViewRow = gvDetail.Rows(e.RowIndex)

6, 取選中行,單元格的值
(1) If currRow IsNot Nothing Then
      txtName.Text = currRow.Cells(1).Value.ToString()
    End If

7, 根據條件改變,行的樣式
(1) 事件=grid1_RowPrePaint()
(2) e.g.
        If reqQty = returnQty Then
            Me.grid1.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Green
        ElseIf returnQty > 0 And returnQty < reqQty Then
            Me.grid1.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Blue
        ElseIf returnQty > reqQty Then
            Me.grid1.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Green
        End If

8, 通過設置屬性,達到單擊行任意處,選擇整行
(1) 屬性-->行為-->SelectionMode=FullRowSelect

9, Grid不可編輯(去掉加載Grid時最上面的空白行)
(1) 其實空白行狀態是——編輯
(2) 屬性-->行為-->AllowUserToAddRows=False

10, 根據條件,設置選中行
(1) SetSelectedRow(gvDetail, txt_Name.Text.Trim(), 1)
(2)     Private Sub SetSelectedRow(ByVal objDataGrid As DataGridView, ByVal sltValue As String, ByVal keyIndex As Integer)
        Dim dvr As DataGridViewRow
        For Each dvr In objDataGrid.Rows
           
            If dvr.Cells(keyIndex).Value.ToString() = sltValue Then
                dvr.Selected = True
                'dvr.DefaultCellStyle.ForeColor = Color.Green
                objDataGrid.CurrentCell = dvr.Cells(keyIndex)
            Else
                dvr.Selected = False
            End If
        Next
    End Sub

11, 10后,取當前行
(1)
' Grid 當前行
Dim gvdr As DataGridViewRow = GetSelectedRow(gvRTDetail)
(2)
    Private Function GetSelectedRow(ByVal objDataGrid As DataGridView) As DataGridViewRow
        Dim dvr As DataGridViewRow = objDataGrid.CurrentRow()
        Return dvr
    End Function

原文地址:https://www.cnblogs.com/htht66/p/1773137.html