使用 eval 在网格视图列中的数据绑定

本文关键字:数据绑定 视图 eval 网格 使用 | 更新日期: 2023-09-27 18:36:20

I hava 网格包含用于显示国名的列。我需要在该列中将值显示为国家/地区名称的前 10 个字母(在印度)。我在项目模板中使用 Eval 函数进行了尝试:

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

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

使用 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);
    }
}

我用

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);
        }