Microsoft KB Archive/812422

= How to programmatically set the DataGrid column width to the longest field by using Visual C# 2005 or Visual C# .NET =

Article ID: 812422

Article Last Modified on 5/10/2007

-

APPLIES TO


 * Microsoft Visual C# 2005 Express Edition
 * Microsoft Visual C# .NET 2002 Standard Edition

-







For a Microsoft Visual Basic .NET version of this article, see 811203.



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 by double-clicking the column separator. Both methods are independent of the font that is used in the DataGrid column fields.

Create a Test Windows Application Project

 * 1) Start Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET.
 * 2) On the File menu, point to New, and then click Project.
 * 3) Under Project Types, click Visual C# Projects, and then click Windows Application under Templates.

Note In Visual Studio 2005, click Visual C# instead of Visual C# Projects.
 * 1) Name the project SampleDataGridColumnWidth, and then click OK.

Data Adapter Configuration Wizard
To configure an OleDbDataAdapter control, follow these steps:  Drag an OleDbDataAdapter control from the toolbox to the form.

Note In Visual Studio 2005, right-click the Toolbox, and then click Choose Items. On the .NET Framework Components tab in the dialog box, select OleDbDataAdapter.

Note If you use the SqlDataAdapter control instead of the OleDbDataAdapter control, follow the analogous steps. In the Data Adapter Configuration Wizard, click Next. Click New Connection. In the Data Link Properties dialog box, select the connection to the SQL Server Northwind database. To do this, follow these steps:  On the Provider tab, click to select Microsoft JET 4.0 OLE DB Provider. On the Connection tab, under Select or enter a database name, click Ellipsis.</li> Locate the database Northwind, click Open, and then click OK.</li></ol> </li> In the Data Adapter Configuration Wizard, click Next.</li> Click to select Use SQL Statement, and then click Next.</li> Use the Query Builder to insert the following SQL statement:

SELECT * FROM Employees

To do this, follow these steps: <ol style="list-style-type: lower-alpha;"> Click Query Builder.</li> In the Add Table dialog box, click to select Employees.</li> 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.)</li> In Employees table, click to select All Columns.</li> To verify the connection, on the Table column, right-click the connection, and then click Run. In the Results pane, Employee table data is displayed.</li> Click OK.</li></ol> </li> Click Finish. Notice that the OleDbConnection1 control is automatically inserted in the project.</li></ol>

Generate a DataSet
Generate a DataSet that is related to OleDbDataAdapter1. To do this, follow these steps: <ol> Right-click OleDbDataAdapter1, and then click Properties.</li> In the Properties window, click Generate Dataset.</li> In the Generate Dataset dialog box, click New, and then name it DataSet1.</li> Verify that the Employees table is selected.</li> Verify that the option Add this dataset to the designer is selected, and then click OK.</li> <li>In Solution Explorer, right-click Form1.cs, and then click View Code.</li> <li> To fill the DataSet, add the following code to the Form1 constructor (this is public Form1): oleDbDataAdapter1.Fill(dataSet11); </li></ol>

Insert a DataGrid and Bind with a DataSet

 * 1) Drag a DataGrid from the toolbox to the form.
 * 2) In the Properties Window, set the DataSource property to DataSet11.Employees.

Implement the Longest Field Search Algorithm
If the DataGrid is bound to a DataSet, it is faster to search in the DataSet for the longest field, than to seach in the DataGrid column. 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 do this, follow these steps: <ol> <li>Drag a button control from the toolbox to the form.</li> <li> Double-click Button1 and add the following code to Button1_Click event: // Get the width of Longest Field int newwidth = LongestField(dataSet11, &quot;Employees&quot;, &quot;Title&quot;);

// Create new Table Style DataGridTableStyle ts = new DataGridTableStyle; ts.MappingName = &quot;Employees&quot;; this.dataGrid1.TableStyles.Clear; this.dataGrid1.TableStyles.Add(ts);

// Assign New Width to DataGrid column this.dataGrid1.TableStyles[&quot;Employees&quot;].GridColumnStyles[&quot;Title&quot;].Width = newwidth; </li> <li> Implement the LongestField function in the Form1 class as follows: private int LongestField (DataSet ds, string TableName, string ColumnName) {   int maxlength = 0; int tot = ds.Tables[TableName].Rows.Count; string straux = &quot;&quot;; int intaux = 0;

Graphics g = dataGrid1.CreateGraphics;

// Take width one balnk space to add to the new width to the Column int offset = Convert.ToInt32(Math.Ceiling(g.MeasureString(&quot; &quot;, dataGrid1.Font).Width));

for (int i=0; i<tot; ++i) {       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) {           maxlength = intaux; }   }// End of For Loop

return maxlength + offset; } </li> <li>On the Debug menu, click Start.</li> <li>Click Button1. Notice that the Title column width is modified to the longest-field size.</li></ol>

<div class="references_section">