How to programmatically set the DataGrid column width to the longest field by using Visual Basic .NET (811203)



The information in this article applies to:

  • Microsoft Visual Basic .NET (2002)
  • Microsoft Visual Basic .NET (2003)

SUMMARY

This step-by-step article describes how to programmatically set the column width of a DataGrid to the longest field of the DataGrid column. You can also do this if you double-click Column Separator. Both of these methods are independent of the font that is used in the DataGrid column fields.

back to the top

Create a Test Windows Application Project

  1. In Visual Studio .NET, point to New on the File menu , and then click Project.
  2. Click Visual Basic Projects, and then click Windows Application.
  3. Name the project SampleDataGridColumnWidth, and then click OK.
back to the top

Data Adapter Configuration Wizard

To configure OleDbDataAdapter1, follow these steps:
  1. Drag an OleDbDataAdapter from the toolbox (located under Data) to Form1.

    Note If you use SqlDataAdapter instead of the OleDbDataAdapter, follow the analogous steps.
  2. In the Data Adapter Configuration Wizard, click Next.
  3. Click New Connection.
  4. In the Data Link Properties dialog box, select the connection to the Northwind database. To do this, follow these steps:
    1. On the Provider tab, click to select theMicrosoft JET 4.0 OLE DB Provider check box.
    2. On the Connection tab, click Ellipsis under Select or enter a database name.
    3. Locate the Northwind database, click Open, and then click OK.
  5. In the Data Adapter Configuration Wizard, click Next.
  6. Click to select Use SQL Statement check box.
  7. Click Next.
  8. Use the Query Builder to insert the SELECT FROM Employees SQL statement. To do this, follow these steps:
    1. Click Query Builder.
    2. In the Add Table dialog box, click to select the Employees table.
    3. Click Add, and then click Close.

      If the Add Table dialog box does not appear, right-click the Query Builder dialog box, and then click Add Table.
    4. In the Employees table, click to select the All Columns check box.
    5. To verify the connection, right-click the connection, and then click Run on the Table column.

      In the results pane, Employee table data is displayed.
    6. Click OK.
  9. Click Finish.

    Notice that the OleDbConnection1 control is automatically inserted into the project.
back to the top

Generate a DataSet

To generate a DataSet that is related to oleDbDataAdapter1, follow these steps:
  1. Right-click OleDbDataAdapter1, and then click Properties.
  2. In the Properties window, click Generate Dataset.
  3. In the Generate Dataset dialog box, click New, and then type the name DataSet1.
  4. Verify that the Employees table is selected.
  5. Verify that the Add this DataSet to the designer option is selected.
  6. Click OK.
  7. In Solution Explorer, right-click Form1.vb, and then click View Code.
  8. To fill the DataSet, append the following code to the Form1 constructor. The Form1 constructor is Public Sub New().
    OleDbDataAdapter1.Fill(DataSet11)
    	
back to the top

Insert a DataGrid and Bind It with DataSet

To insert a DataGrid and bind it with DataSet, follow these steps:
  1. Drag a DataGrid from the toolbox (located under Windows Forms) to Form1.
  2. In the Properties window, set the DataSource property to DataSet11.Employees.
back to the top

Implement the Longest Field Search Algorithm

To measure the width of the specified string that is drawn with the specified font, use the MeasureString method of the graphics object that is retrieved from the DataGrid. To Search in the DataSet for the longest field is faster than when you search in the DataGrid column if the DataGrid is bound to a DataSet. To search in the DataSet for the longest field, follow these steps:
  1. Drag a button from the toolbox (located under Windows Forms) to Form1.
  2. Double-click Button1, and then add the following code to the Button1_Click event:
    ' Get the width of the Longest Field.
    Dim newwidth As Integer = LongestField(DataSet11, "Employees", "Title")
    
    ' Create new Table Style.
    Dim ts As New DataGridTableStyle()
    ts.MappingName = "Employees"
    DataGrid1.TableStyles.Clear()
    DataGrid1.TableStyles.Add(ts)
    
    ' Assign New Width to DataGrid column.
    DataGrid1.TableStyles("Employees").GridColumnStyles("Title").Width = newwidth 
  3. Implement the LongestField() function in the Form1 class, as follows:
    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 = DataGrid1.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(" ", DataGrid1.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, DataGrid1.Font).Width))
       If (intaux > maxlength) Then
        maxlength = intaux
       End If
      Next
    
      Return maxlength + offset
    
     End Function
  4. On the Debug menu, click Start.
  5. Click Button1.

    Notice that the Title column width is modified to the longest-field size.
back to the top

REFERENCES

For additional information, click the following article number to view the article in the Microsoft Knowledge Base:

313482 INFO: Roadmap for Windows Forms Data Binding


For more information, visit the following Microsoft Web site:

Data Binding with Windows Forms and ADO.NET
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/databindingadonet.asp

back to the top

Modification Type:MinorLast Reviewed:2/3/2006
Keywords:kbvs2005doesnotapply kbvs2005swept kbHOWTOmaster kbCtrl kbDataBinding kbWindowsForms kbui kbDataObject kbhowto kbcode KB811203 kbAudDeveloper