DataTable dt=new DataTable();
dt.Columns.Add(new DataColumn("Departure Date",typeof(string)));
dt.Columns.Add(new DataColumn("Route", typeof(string)));
dt.Columns.Add(new DataColumn("Hotel", typeof(string)));

DataRow dr;
dr=dt.NewRow();
dr[0]="DepartureDate";
dr[1]="Route";
dr[2]="Hotel";dt.Rows.Add(dr); this.grdTD.DataSource=dt;
象这样绑定数据的datagrid,如何设定列的宽度?
thank you.

解决方案 »

  1.   

    #region 使grid根据内容适应列宽
    public static  void SizeColumnsToContent (System.Windows.Forms.DataGrid dataGrid, int nRowsToScan,System.Data.DataTable _dataTable) 
    {
    // Create graphics object for measuring widths.
    Graphics Graphics = dataGrid.CreateGraphics(); // Define new table style.
    DataGridTableStyle tableStyle = new DataGridTableStyle(); try
    {
    System.Data .DataTable dataTable =_dataTable; if (-1 == nRowsToScan)
    {
    nRowsToScan = dataTable.Rows.Count;
    }
    else
    {
    // Can only scan rows if they exist.
    nRowsToScan = System.Math.Min(nRowsToScan, dataTable.Rows.Count);
    } // Clear any existing table styles.
    dataGrid.TableStyles.Clear(); // Use mapping name that is defined in the data source.
    tableStyle.MappingName = dataTable.TableName;
    //设置grid中蓝白交错效果
    tableStyle.AlternatingBackColor =Color.LightBlue  ;
    tableStyle.BackColor =Color.White ; // 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); // Change width, if data width is wider than header text width.
    // Check the width of the data in the first X rows.
    DataRow dataRow;
    for (int iRow = 0; iRow < nRowsToScan; iRow++)
    {
    dataRow = dataTable.Rows[iRow]; if (null != dataRow[dataColumn.ColumnName])
    {
    int iColWidth = (int)(Graphics.MeasureString(dataRow.ItemArray[iCurrCol].ToString(), dataGrid.Font).Width);
    iWidth = (int)System.Math.Max(iWidth, iColWidth);
    }
    }
    columnStyle.Width = iWidth + 4; // 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();
    }
    }
    #endregion