转自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;
}