c# - 如何使用阅读更多链接限制 GridView 中的标签字符串长度?

标签 c# asp.net string gridview

目前我是这样用的...

<asp:TemplateField HeaderText="Description">
 <ItemTemplate>
      <asp:Label ID="lblDescription" runat="server"
                Text='<%# Limit(Eval("Description"),40) %>' >
      </asp:Label>
 </ItemTemplate>

辅助函数:

public static string Limit(object Desc, int length)
{
    StringBuilder strDesc = new StringBuilder();
    strDesc.Insert(0, Desc.ToString());

    if (strDesc.Length > length)
        return strDesc.ToString().Substring(0, length) + "..." + [Read More];
    else return strDesc.ToString();
}

但我不知道如何放置 [Read More] 链接...

最佳答案

做这样的事情。

标记

<asp:TemplateField HeaderText="Description">
 <ItemTemplate>
      <asp:Label ID="lblDescription" runat="server"
                Text='<%# Limit(Eval("Description"),40) %>' 
                Tooltip='<%# Eval("Description") %>'>
      </asp:Label>
      <asp:LinkButton ID="ReadMoreLinkButton" runat="server"
                Text="Read More"
                Visible='<%# SetVisibility(Eval("Description"), 40) %>'
                OnClick="ReadMoreLinkButton_Click">
      </asp:LinkButton>
 </ItemTemplate>
</asp:TemplateField>

代码隐藏

protected bool SetVisibility(object desc, int maxLength)
{
    var description = (string)desc;
    if (string.IsNullOrEmpty(description)) { return false; }
    return description.Length > maxLength;
}

protected void ReadMoreLinkButton_Click(object sender, EventArgs e)
{
    LinkButton button = (LinkButton)sender;
    GridViewRow row = button.NamingContainer as GridViewRow;
    Label descLabel = row.FindControl("lblDescription") as Label;
    button.Text = (button.Text == "Read More") ? "Hide" : "Read More";
    string temp = descLabel.Text;
    descLabel.Text = descLabel.ToolTip;
    descLabel.ToolTip = temp;
}

protected string Limit(object desc, int maxLength)
{
    var description = (string)desc;
    if (string.IsNullOrEmpty(description)) { return description; }
    return description.Length <= maxLength ? 
        description : description.Substring(0, maxLength)+ "...";
}

关于c# - 如何使用阅读更多链接限制 GridView 中的标签字符串长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6012942/

相关文章:

c# - 通过 MethodInfo 调用方法

c# - 是否可以在 C# 中使用 getter/setter 模板?

c# - 结构隐式vs空构造函数

c# - 如何使用Dockerfile覆盖ASP.NET Core连接字符串

c - 将 4 行字符串放在一起并计算单词数

Java - 在类中添加支持以允许乘法

c# - AntiXSS 不会清理未封闭的 html 标签

asp.net - MVC3 项目中 Url.Action 中空对象引用的问题

javascript,搜索我的名字

java - Java 中的 UTF-8 和 UTF-16