轉自http://blog.csdn.net/qiujiahao/archive/2007/08/09/1733347.aspx
public void SetGridViewWidth(GridView gridview1)
{
int rowcount = gridview1.Rows.Count; //行數
int colcount = gridview1.Columns.Count; //列數
int i=0,j=0;
int[] cellwidth = new int[colcount]; //數組用來儲存各個列的最大字元數
int gridviewwidth = 0; //GridView寬度
Unit width = 0;
string temp = null;
int tempLength = 0;
for (i = 0; i < rowcount; i++) //迴圈資料項目,獲得各個列的最大字元寬度
{
for (j = 0; j < colcount; j++)
{
temp = gridview1.Rows[i].Cells[j].Text;
tempLength = LengthOfLetter(temp); //LengthOfLetter()返回含中文的字串字元寬度,1個漢字2個字元寬
if (cellwidth[j] < tempLength)
{
cellwidth[j] = tempLength; //儲存較大寬度值
}
}
}
for (j = 0; j < colcount; j++)
{
if (gridview1.HeaderRow.Visible == true) //如果GridView表頭可見,將表頭列寬參與比較 {
temp = gridview1.HeaderRow.Cells[j].Text;
tempLength = LengthOfLetter(temp);
if (cellwidth[j] < tempLength)
{
cellwidth[j] = tempLength;
}
if (gridview1.FooterRow.Visible == true) //如果GridView表尾可見,將表尾列寬參與比較 {
temp = gridview1.FooterRow.Cells[j].Text;
tempLength = LengthOfLetter(temp);
if (cellwidth[j] < tempLength)
{
cellwidth[j] = tempLength;
}
}
for (j = 0; j < colcount; j++)
{
if (gridview1.Columns[j].Visible == true)
{
//將顯示的列的各列最大字元寬度相加 {
gridviewwidth += cellwidth[j];
}
}
width = gridviewwidth * 5; //GridView最大字元數乘於一個字元顯示寬度得到GridView顯示寬度
if (gridview1.Width.Value < width.Value) //如果在介面上已經設定了GridView的寬度,將動態求的寬度和頁面上的
{ //初始化寬度比較,如果初始化寬度較小則將寬度設定為新調整的寬度。
gridview1.Width = width;
}
}
//含有中文的字串等效英文字串顯示長度
public int LengthOfLetter(string temp)
{
int length = temp.Length;
int newlength = temp.Length;
for (int i = 0; i < length; i++) //遍曆字串每個字元
{
if (IsChineseLetter(temp, i)) //IsChineseLetter()判斷是否為中文字元,是則寬度加1
{
newlength++;
}
}
return newlength;
}
//判斷是否為中文字元
public bool IsChineseLetter(string input,int index)
{
int code = 0;
int chfrom = Convert.ToInt32("4e00", 16); //範圍(0x4e00~0x9fff)轉換成int(chfrom~chend)
int chend = Convert.ToInt32("9fff", 16);
if (input != "")
{
code = Char.ConvertToUtf32(input, index); //獲得字串input中指定索引index處字元unicode編碼
if (code >= chfrom && code <= chend)
{
return true; //當code在中文範圍內返回true
}
else
{
return false ; //當code不在中文範圍內返回false
}
}
return false;
}