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

Article translations Article translations
Article ID: 812422 - View products that this article applies to.
For a Microsoft Visual Basic .NET version of this article, see 811203.
Expand all | Collapse all

On This Page

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.
  4. Name the project SampleDataGridColumnWidth, and then click OK.

Data Adapter Configuration Wizard

To configure an OleDbDataAdapter control, follow these steps:
  1. 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.
  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 SQL Server Northwind database. To do this, follow these steps:
    1. On the Provider tab, click to select Microsoft JET 4.0 OLE DB Provider.
    2. On the Connection tab, under Select or enter a database name, click Ellipsis.
    3. Locate the database Northwind, click Open, and then click OK.
  5. In the Data Adapter Configuration Wizard, click Next.
  6. Click to select Use SQL Statement, and then click Next.
  7. Use the Query Builder to insert the following SQL statement:
    SELECT * FROM Employees
    To do this, follow these steps:
    1. Click Query Builder.
    2. In the Add Table dialog box, click to select Employees.
    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 Employees table, click to select All Columns.
    5. 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.
    6. Click OK.
  8. Click Finish. Notice that the OleDbConnection1 control is automatically inserted in the project.

Generate a DataSet

Generate a DataSet that is related to OleDbDataAdapter1. To do this, 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 name it DataSet1.
  4. Verify that the Employees table is selected.
  5. Verify that the option Add this dataset to the designer is selected, and then click OK.
  6. In Solution Explorer, right-click Form1.cs, and then click View Code.
  7. To fill the DataSet, add the following code to the Form1 constructor (this is public Form1()):
    oleDbDataAdapter1.Fill(dataSet11);
    	

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:
  1. Drag a button control from the toolbox to the form.
  2. Double-click Button1 and add the following code to Button1_Click event:
    // Get the width of Longest Field
    int newwidth = LongestField(dataSet11, "Employees", "Title");
    
    // Create new Table Style
    DataGridTableStyle ts = new DataGridTableStyle();
    ts.MappingName = "Employees";
    this.dataGrid1.TableStyles.Clear();
    this.dataGrid1.TableStyles.Add(ts);
    
    // Assign New Width to DataGrid column
    this.dataGrid1.TableStyles["Employees"].GridColumnStyles["Title"].Width = newwidth;
    
  3. 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 = "";
    	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(" ", 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;
    }
  4. On the Debug menu, click Start.
  5. Click Button1. Notice that the Title column width is modified to the longest-field size.

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 additional information, see the following Microsoft Developer Network (MSDN) Web site:
Data Binding with Windows Forms and ADO.NET
http://msdn2.microsoft.com/en-us/library/ms973824.aspx

Properties

Article ID: 812422 - Last Review: May 10, 2007 - Revision: 3.4
APPLIES TO
  • Microsoft Visual C# 2005 Express Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
Keywords: 
kbhowtomaster kbctrl kbdatabinding kbwindowsforms kbui KB812422

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com