vs2008

设计页:

                                          <asp:TemplateField>
                                                <ItemTemplate>
                                                    <a href='test.aspx?newsId=<%#Eval("id") %>'target="_blank">
                                                     <%# CutString(Convert.ToString(Eval("content")), 30)%></a>
                                                </ItemTemplate>
                                            </asp:TemplateField>

代码页:

    /// <summary>
    /// 如果长度大于totalLen,则截取len长度,其余...添充
    /// </summary>
    /// <param name="s">要截取的字符串</param>
    /// <param name="len">截取的长度</param>
    /// <param name="totalLen">添充.后的总长度</param>
    /// <returns></returns>
    public string CutString(string s, int len)
    {
        int totalLen = 33;
        string result = ""; //最终返回的结果
        int byteLen = System.Text.Encoding.Default.GetByteCount(s);  //单字节字符长度
        if (byteLen <= totalLen) return s;
        int charLen = s.Length; //把字符平等对待时的字符串长度
        int byteCount = 0;  //记录读取进度{中文按两单位计算}
        int pos = 0;    //记录截取位置{中文按两单位计算}
        if (byteLen > len)
        {
            for (int i = 0; i < charLen; i++)
            {
                if (byteCount >= len)   //到达指定长度时,记录指针位置并停止
                {
                    pos = i;
                    break;
                }
                if (Convert.ToInt32(s.ToCharArray()[i]) > 255)  //遇中文字符计数加2
                    byteCount += 2;
                else         //按英文字符计算加1
                    byteCount += 1;

            }
            result = s.Substring(0, pos) + "".PadLeft(totalLen - byteCount, '.');
        }
        else
            result = s;

        return result;
    }

posted on 2013-11-14 09:36  御不凡  阅读(334)  评论(0编辑  收藏  举报