DataGridView Notes:
Click here for DataGridViewFunctions.vb
download
Sample Form_Load event…
Public Class Form1
Dim DGV1_DataAdapter As New OleDbDataAdapter
Dim DGV1_BindingSource1 As New BindingSource
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DGVLoadBindingSourceWithSQLResults_OLEDB(DataGridView1, "Select * From Snippets", DGV1_DataAdapter, DGV1_BindingSource1)
FormatGrid()
End Sub
In Windows Forms, it’s best to decare the DataAdapter and BindingSource at the top of the Form…
Public Class Form1
.
.
Dim DGV1_DataAdapter As New OleDbDataAdapter
Dim DGV1_BindingSource1 As New BindingSource
Sample Last Button Click Event…
Private Sub
cmdMoveLast_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles
cmdMoveLast.Click
DGVMoveLast(DGV1_BindingSource1)
End Sub
Rendering errors in the DataGridView can be handled this way…
Private Sub DataGridView1_DataError(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles DataGridView1.DataError
Dim sError As String = UCase(Trim(e.Context.ToString))
If sError = "DISPLAY" Then
'do nothing
Else
MessageBox.Show("Datagridview error:" & sError)
End If
End Sub
Contents of the current cell can be viewed this way….
Private Sub DataGridView1_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.CurrentCellChanged
Try
TextBox1.Text = DataGridView1.CurrentRow.Cells("FieldName").Value.ToString
Catch ex As Exception
End Try
End Sub
Some common formatting commands…
Sub FormatGrid()
'Allow users to add rows...
DataGridView1.AllowUserToAddRows = False
'Column header text...
DataGridView1.Columns(1).HeaderText = "Hello World"
'Grid backcolor...
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Honeydew
DataGridView1.Columns(2).DefaultCellStyle.BackColor = Color.SlateGray
'Column width...
DataGridView1.Columns(2).Width = 400
'Row height...
DataGridView1.Rows(1).Height = 50
'Column visibility...
DataGridView1.Columns("Id_Snippet").Visible = False
'Column position in grid...
DataGridView1.Columns("EntryDate").DisplayIndex = 7
End Sub
Paging…
Private Sub
GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewPageEventArgs) Handles
GridView1.PageIndexChanging
'Make sure you've set the GridView1.AllowPaging = True and
GridView1.PageSize = N
GridView1.PageIndex = e.NewPageIndex
LoadGrid(ddlType.Text,
ddlLang.Text, ddlExam.Text)
End Sub