/// /// Sets the Column width and visual properties of a DataGrid /// /// private void sizeColumnsToHeaderText(DataGrid dataGrid) { // Create graphics object for measuring widths. Graphics Graphics = dataGrid.CreateGraphics(); // Define new table style. DataGridTableStyle tableStyle = new DataGridTableStyle(); //Set up the visual style tableStyle.AlternatingBackColor = System.Drawing.SystemColors.Control; tableStyle.BackColor = System.Drawing.SystemColors.Control; tableStyle.ForeColor = System.Drawing.Color.MidnightBlue; tableStyle.GridLineColor = System.Drawing.Color.White; tableStyle.HeaderBackColor = System.Drawing.Color.MidnightBlue; tableStyle.HeaderFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); tableStyle.HeaderForeColor = System.Drawing.Color.WhiteSmoke; tableStyle.LinkColor = System.Drawing.Color.Teal; tableStyle.SelectionBackColor = Color.Black; tableStyle.SelectionForeColor = Color.Red; try { DataSet dS = (DataSet)dataGrid.DataSource; DataTable dataTable = (DataTable)dS.Tables[0]; // Clear any existing table styles. dataGrid.TableStyles.Clear(); // Use mapping name that is defined in the data source. tableStyle.MappingName = dataTable.TableName; // Now create the column styles within the table style. DataGridTextBoxColumn columnStyle; int iWidth; for (int iCurrCol = 0; iCurrCol < dataTable.Columns.Count; iCurrCol++) { DataColumn dataColumn = dataTable.Columns[iCurrCol]; columnStyle = new DataGridTextBoxColumn(); columnStyle.TextBox.Enabled = true; columnStyle.HeaderText = dataColumn.ColumnName; columnStyle.MappingName = dataColumn.ColumnName; // Set width to header text width. iWidth = (int)(Graphics.MeasureString(columnStyle.HeaderText, dataGrid.Font).Width); //sets width by prog columnStyle.Width = iWidth + 14; //manually sets the width if ((columnStyle.HeaderText == "ID")|| columnStyle.HeaderText == "CDnr") columnStyle.Width = 40; if ((columnStyle.HeaderText == "Filmnamn") || columnStyle.HeaderText == "Anteckningar") columnStyle.Width = 181; if (columnStyle.HeaderText == "kategori") columnStyle.Width = 80; // Add the new column style to the table style. tableStyle.GridColumnStyles.Add(columnStyle); // Add the new table style to the data grid. dataGrid.TableStyles.Add(tableStyle); } } catch (Exception e) { MessageBox.Show(e.Message); } finally { Graphics.Dispose(); } }