Dynamically Setting DataGrid Column Widths to the Longest Field; Using Visual J#.Net

SUMMARY

This step-by-step article describes how to dynamically set the column widths of a DataGrid to the longest field of the

DataGrid column. This method is independent of the font that is used in the DataGrid column fields.

 

Create a Test Windows Application Project

1.

Start Visual Studio .NET.

2.

On the File menu, point to New, and then click Project.

3.

Under Project Types, click Visual J# Projects, and then click Windows Application under Templates.

4.

Name the project SampleDataGridColumnWidth, and then click OK.

 

Create a DataGrid on the Form

1

Click on the form and change the Size property to 600, 400

2

From the ToolBox, drag the DataGrid to your form.

3

Click on the DataGrid and change the Dock property to the Center Square. (The DataGrid now fills up the entire form.

 

Fill The DataGrid

1.

Use any method you would like to fill the DataGrid, continue to the next step to fill it by adding rows, columns and data.

2.

Double Click on Form1 and add some columns and data

 

            DataSet myDataSet = new DataSet("Person");

            DataTable myDataTable = new DataTable("Person");

 

            //Add Columns

            myDataTable.get_Columns().Add("First Name");

            myDataTable.get_Columns().Add("Last Name");

            myDataTable.get_Columns().Add("Age");

           

            Object[] myValues = new Object[3];

 

            //Create and add rows

            myValues[0] = "Abe";

            myValues[1] = "Lincoln";

            myValues[2] = "195";

            myDataTable.get_Rows().Add(myValues);

 

            myValues[0] = "Fredrick";

            myValues[1] = "VonPlait";

            myValues[2] = "46";

            myDataTable.get_Rows().Add(myValues);

 

            //Insert into datagrid

            myDataSet.get_Tables().Add(myDataTable);

            dataGrid1.set_DataSource(myDataSet);

            dataGrid1.set_DataMember("Person");

3.

Click back to your Form1.jsl [Design] tab.

4.

Run the program to make sure there are columns and data

 

Add the Longest Field Function to the class

1.

Double Click on Form1 and add these functions below the Form1_Load procedure:

      // Function converted to J# from:

           //http://support.microsoft.com/default.aspx?scid=kb;en-us;812422

      public int longestField (DataGrid dgd,int columnNumber)

      {

            int maxlength = 0;

            int tot = ((DataSet)(dgd.get_DataSource())).get_Tables().

                        get_Item(0).get_Rows().get_Count();

            String straux = "";

            int intaux = 0;

            Graphics g = dgd.CreateGraphics();

            // Take width of one blank space to add to the new width to the Column

            int offset = System.Convert.ToInt32(System.Math.Ceiling(

                              g.MeasureString(" ", dgd.get_Font()).get_Width()));

 

            for (int i=0; i<tot; ++i)

            {

                  straux = dgd.get_Item(i, columnNumber).ToString();

                  // Get the width of Current Field String according to the Font

                 

                  intaux = System.Convert.ToInt32(System.Math.Ceiling(

                                 g.MeasureString(straux, dgd.get_Font()).get_Width()));

                  if (intaux > maxlength)

                  {

                        maxlength = intaux;

                  }

            }// End of For Loop

            return maxlength + offset;

      }

 

Format The DataGrid

1

Now that the necessary tools are there, you just need to tell it to format what you want formatted.

2

We will write another function that iterates through the datagrid columns and formats them. This function will make the

Columns the width of the longest field plus one space, unless the header is bigger, in which case it will resize to the

Width of the header plus one space.

      public void setColWidths(DataGrid dgd)

      {

            DataSet myDataSet = ((DataSet)dataGrid1.get_DataSource());

            String tableName = myDataSet.get_Tables().get_Item(0).get_TableName();

      int colCount = myDataSet.get_Tables().get_Item(0).get_Columns().get_Count();

 

            System.Windows.Forms.DataGridTableStyle ts = new

            System.Windows.Forms.DataGridTableStyle();

            System.Windows.Forms.DataGridTextBoxColumn tc = null;

 

            ts.set_MappingName(tableName);

            Graphics g = dgd.CreateGraphics();

            int offset = System.Convert.ToInt32(System.Math.Ceiling(

                  g.MeasureString(" ", dgd.get_Font()).get_Width()));

     

            for (int i = 0; i < colCount; i++)

            {

                  String colName = myDataSet.get_Tables().get_Item(0).get_Columns()

                                                .get_Item(i).get_ColumnName().ToString();

                  tc = new System.Windows.Forms.DataGridTextBoxColumn();

                  tc.set_MappingName(colName);

                  tc.set_HeaderText(colName);

 

                  int length = this.longestField(dgd,i);

                  int intaux = System.Convert.ToInt32(System.Math.Ceiling(

                                 g.MeasureString(colName, dgd.get_Font()).get_Width()));

 

                  int headerLength = intaux + offset;

                  if (length < headerLength)

                        length = headerLength;

 

                  tc.set_Width( length );

 

                  // Adds the column style to the TableStyles

                  ts.get_GridColumnStyles().Add( tc );

            }

            // Adds the tablestyle to the DataGrid.

            dgd.get_TableStyles().Clear();

            dgd.get_TableStyles().Add( ts );

      }

3

All that is left is to call your function.  Add this code to the bottom of your Form1_Load procedure:

            this.setColWidths(dataGrid1);

4

Now run the program and make sure the columns are the right size.