1

我有一个网格,其中包含一个用于显示国名的列。我需要将该列中的值显示为 contrycode-first 10 个国家名称的字母(印度)。我在项目模板中使用 Eval 函数进行了尝试:

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

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

4

2 回答 2

6

您可以使用三元运算符?

<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);
    }
}
于 2012-06-06T10:31:10.877 回答
0

我是用

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label countryNameLabel = (Label)e.Row.FindControl("CountryNameLabel");
                countryNameLabel.ToolTip = countryNameToolTip(countryNameLabel.Text);
                countryNameLabel.Text = countryNameDisplay(countryNameLabel.Text);
            }
        }

protected string countryNameDisplay(string key)
        {
            CustomerBusinessProvider business = new CustomerBusinessProvider();
            string country = business.CountryName(key);
            country = key + "-" + country;
            if (country.Length > 10)
            {
                country = country.Substring(0, 10) + "...";
            }
            return country;
        }
        protected string countryNameToolTip(string key)
        {
            CustomerBusinessProvider business = new CustomerBusinessProvider();
            return business.CountryName(key);
        }
于 2012-06-06T12:53:44.687 回答