Winforms DataGridView Notes

It is not often when I have to go and create a DataGridView in Winforms so here are some notes.   Sadly we are stuck in .net 2.0.
  • I find it easier to add the columns manually through the designer that the datagridview will hold.  Ids, text fields, buttons, etc.  I have a custom CalendarColumn as well.
  •  The main fields of the columns in the dgv that are used are the HeaderText, Visible, DefaultCellStyle->Format, DataPropertyName, Name, AutoSizeMode, and Width.  In case of Button UseColumnTextForButtonValue (remember to have the FlatStyle = Standard).
  • When accessing data, the values could be nothing or DBNull.value, depending if it is a new row or not.  So will need a lot of testing for DBNull or Nothing.
  • Adding data to dgv could be done inside the dgv, but having fields outside to add to the grid is feasible as well.
  • Modifing inside or outside grid can work.
  • Deleting seems to work well inside.  
  • Rebinding works well after a changing data (aka getting datatable and setting it to the datasource)
  • If I need the ID afterward remember to us OUTPUT INSERTED.ID and use .ExecuteScalar, and set it to an variable of type integer (not object).
Some snippets



      If (row.Cells("colExpireDate").Value Is DBNull.Value) Then
                    sIncident.ExpireDate = Nothing
                Else
                    sIncident.ExpireDate = DateTime.Parse(row.Cells("colExpireDate").Value)
                End If


  Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As DataGridViewCellEventArgs) _
                                           Handles dgvSI.CellContentClick
        Dim senderGrid = DirectCast(sender, DataGridView)

        If TypeOf senderGrid.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso e.RowIndex >= 0 Then
            If dgvSI.Rows(e.RowIndex).Cells("colID").Value IsNot DBNull.Value And dgvSI.Rows(e.RowIndex).Cells("colID").Value IsNot Nothing Then
                Dim rowID As Integer = Integer.Parse(dgvSI.Rows(e.RowIndex).Cells("colID").Value)
                Dim strProc As String = "spDelete_SecurityIncidents"
                SqlHelper.ExecuteNonQuery(My.MySettings.Default.ApplicationDBConn, strProc, rowID)
                DataBindSecurityIncidentDGV()
            End If
        End If
    End Sub
End Class

Comments

Popular posts from this blog

Asp.net Publishing Broke Site - "App_WebReferences is not allowed because the application is precompiled"

Telerik - Custom Group Footers In RadGrid