close

     /// <summary>
        /// datagrid 欄寬自動適應文字寬度
        /// </summary>
        /// <param name="oDataGrid">DataGrid</param>
        /// <param name="oData">DataTable</param>
        /// <param name="nColumnPadding">nColumnPadding  ex: 10 </param>
        private void AutoFitDataGrid(DataGrid oDataGrid, DataTable oData, int nColumnPadding)
        {
            int nColumnWidth;
            int nHeaderWidth;
            Graphics g = null;
            string strMax = "";
            string strValue;

            DataGridTableStyle dgts = new DataGridTableStyle(true);
            dgts.MappingName = oData.TableName;
            oDataGrid.TableStyles.Clear();
            oDataGrid.TableStyles.Add(dgts);

    

            try
            {
                g = CreateGraphics();

                foreach (DataGridColumnStyle oColumnStyle in oDataGrid.TableStyles[0].GridColumnStyles)
                {

                    int i = 0;
                    foreach (DataRow row in oData.Rows)
                    {
                        try
                        {
                            strValue = row[oColumnStyle.MappingName].ToString().Trim();
                            if (strMax.Length < strValue.Length)
                                strMax = strValue;
                        }
                        catch
                        {
                            strMax = "";
                        }
                    }

                   

                    nColumnWidth = g.MeasureString(strMax, oDataGrid.Font).ToSize().Width + nColumnPadding;
                    nHeaderWidth = g.MeasureString(oColumnStyle.HeaderText, oDataGrid.HeaderFont).ToSize().Width + nColumnPadding;

                    if (nHeaderWidth > nColumnWidth)
                        oColumnStyle.Width = nHeaderWidth;
                    else
                        oColumnStyle.Width = nColumnWidth;

 


                    strMax = "";
                }
            }
            catch (Exception ex)
            {
              //  throw;
            }
            finally
            {
                if (g != null)
                    g.Dispose();
            }
        }

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 11 的頭像
    11

    冠霖的部落格

    11 發表在 痞客邦 留言(0) 人氣()