我有一个包含用于显示国家/地区名称的列的网格。我需要将该列中的值显示为 contrycode-first 10 letters of country name (in-India)。我在项目模板中使用 Eval 函数尝试了它:
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="CountryNameLabe" runat="server" Text='<%# Eval("CorporateAddressCountry").SubString(0,6) %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
但是显示错误。 我可以在 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);
}
}
关于c# - 使用 eval 在 gridview 列中进行数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10912389/