c#
  • asp.net
  • 2012-06-06 195 views 1 likes 
    1

    我hava网格包含一列显示countrynames。我需要在列contrycode一国名(在印度)。我尝试过使用eval函数与项模板的10个字母来显示值:数据绑定在gridview列使用eval

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

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

    +0

    代码在哪里? –

    +0

    @PanagiotisKanavos:它在那里,它只是没有显示,因为它有HTML标记。 –

    +3

    它给你什么错误? –

    回答

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

    这假定他的错误与字符串不够长有关。如果他的字段正在产生'DBNull',这仍然会抛出异常。 –

    +0

    我想将它与另一个国家/地区代码连接在一起:例如:美国 - 美国的美国... –

    +0

    @JoelEtherton:是的,但如果不是这种情况,它还提供了一种调试代码的方法,以查看例外的实际原因。 –

    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); 
         } 
    
    相关问题