c# - 使用 eval 在 gridview 列中进行数据绑定(bind)

标签 c# asp.net

我有一个包含用于显示国家/地区名称的列的网格。我需要将该列中的值显示为 contrycode-first 10 letters of country name (in-India)。我在项目模板中使用 Eval 函数尝试了它:

<asp:TemplateField>
  <ItemTemplate>
      <asp:Label ID="CountryNameLabe" runat="server" Text='<%# Eval("CorporateAddressCountry").SubString(0,6) %>' ></asp:Label>
  </ItemTemplate>
</asp:TemplateField>

但是显示错误。 我可以在 eval 中使用自定义函数吗? 请帮忙

最佳答案

可以使用三元运算符?:

<asp:Label ID="CountryNameLabel" runat="server" 
    Text='<%# Eval("CorporateAddressCountry").ToString().Length <= 10 ? Eval("CorporateAddressCountry") : Eval("CorporateAddressCountry").ToString().Substring(0,10) %>' >
</asp:Label>

另一种,在我看来更具可读性,方法是使用 GridView 的 RowDataBound事件:

protected void Gridview1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        var row = (DataRowView) e.Row.DataItem;
        var CountryNameLabel = (Label) e.Row.FindControl("CountryNameLabel");
        String CorporateAddressCountry = (String) row["CorporateAddressCountry"];
        CountryNameLabel.Text = CorporateAddressCountry.Length <= 10 
                               ? CorporateAddressCountry
                               : CorporateAddressCountry.Substring(0, 10);
    }
}

关于c# - 使用 eval 在 gridview 列中进行数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10912389/

相关文章:

asp.net - 如何使用 ASP.NET 和 iframe 跨域对用户进行身份验证?

c# - WebAPI 的 WPF 客户端 - 如何处理身份验证密码

c# - 如何对科学数字使用按位运算符?

c# - 什么是 SUT,它从何而来?

c# - 在 silverlight 和 HTML5 之间切换

javascript - 链接按钮在 Google Chrome 中不起作用

c# - IIS 10.0 最大请求长度 .NET MVC

c# - 正确的 C# 命名空间用法是什么?

我的应用程序的 C# 或 Python

asp.net - 用户控制命令按钮事件第一次未触发