Question help~~~ Datagrid with automatic width


New member
Sep 20, 2010
Programming Experience
Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sql As String
Dim MyDataSet = New DataSet
Dim dt As DataTable
sql = "SELECT tbl_requestor.r_Name as Requestor, tbl_request.nr_location as Location, tbl_request.nr_problem as Problem, tbl_request.nr_remark as Remark FROM tbl_request LEFT JOIN tbl_requestor ON tbl_request.nr_r_ID = tbl_requestor.r_ID"
Dim MyDA = New MySqlDataAdapter(sql, conn)
Dim MyCB As MySqlCommandBuilder = New MySqlCommandBuilder(MyDA)
MyDA.Fill(MyDataSet, "tbl_request")
Dim newwidth As Integer = LongestField(MyDataSet, "tbl_request", "Requestor")
Dim ts As New DataGridTableStyle()
ts.MappingName = "tbl_request"

dgNewRequest.TableStyles("tbl_request").GridColumnStyles("Requestor").Width = newwidth
dt = MyDataSet.Tables(0)
dgNewRequest.DataSource = dt

Catch ex As MySqlException
End Try
End Sub

Private Function LongestField(ByVal ds As DataSet, ByVal TableName As String, ByVal ColumnName As String) As Integer

Dim maxlength As Integer = 0
Dim g As Graphics = dgNewRequest.CreateGraphics()

' Take width of one blank space and add to the new width of the Column.
Dim offset As Integer = Convert.ToInt32(Math.Ceiling(g.MeasureString(" ", dgNewRequest.Font).Width))

Dim i As Integer = 0
Dim intaux As Integer
Dim straux As String
Dim tot As Integer = ds.Tables(TableName).Rows.Count

For i = 0 To (tot - 1)
straux = ds.Tables(TableName).Rows(i)(ColumnName).ToString()
' Get the width of Current Field String according to the Font.
intaux = Convert.ToInt32(Math.Ceiling(g.MeasureString(straux, dgNewRequest.Font).Width))
If (intaux > maxlength) Then
maxlength = intaux
End If

Return maxlength + offset

End Function

Hi All,
This is my code for setting the width for datagrid, but i have this error
NullReferenceException was unhandled at "dgNewRequest.TableStyles("tbl_request").GridColumnStyles("Requestor").Width = newwidth"

Can anyone help? thanks~~~
Top Bottom