使用eval在gridview列中进行数据绑定

时间:2012-06-06 10:26:19

标签: c# asp.net

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

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

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

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分: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);
        }