我通常用GridView綁定datatable,由于需要動態綁定到不同的datatable所以需要動態調整GridView的寬度。所以寫了這個函數實現該功能。GridView的寬度需要根據各個列中最大寬度來累加獲得。在求各個列的最大字符寬度的時候需要對中文和英文加以區分,因為字符串“序號”和“id”的length屬性都為2,但是顯示的時候一個漢字占據的寬度卻相當于2個英文字符。要想達到準確的顯示效果,我對含有漢字的字符串根據漢字的數目確定該字符串等價英文字符的長度,例如字符串“序號id”的length屬性為4,我自己通過函數獲得的長度為6.確定了每列的最大字符數后,累加即可獲得GridView的寬度字符,然后乘于一個字符在屏幕上的顯示寬度oneLetterLength常量后就是GridView寬度。
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 * oneLetterLength; //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;
}
|
新聞熱點
疑難解答