我hava网格包含一个用于显示国家/地区名称的列.我需要在该列中显示值作为contrycode - 国家名称的前10个字母(在印度).我在项目模板中使用Eval函数进行了尝试:
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="CountryNameLabe" runat="server" Text='<%# Eval("CorporateAddressCountry").SubString(0,6) %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Run Code Online (Sandbox Code Playgroud)
但它显示错误.我可以在eval中使用自定义函数吗?请帮忙
您可以使用三元运算符?:
<asp:Label ID="CountryNameLabel" runat="server"
Text='<%# Eval("CorporateAddressCountry").ToString().Length <= 10 ? Eval("CorporateAddressCountry") : Eval("CorporateAddressCountry").ToString().Substring(0,10) %>' >
</asp:Label>
Run Code Online (Sandbox Code Playgroud)
在我看来,另一个更具可读性的方法是使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26869 次 |
| 最近记录: |