C# 使用 eval 在 gridview 列中绑定数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10912389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Data binding in gridview column using eval
提问by Rn.
I hava grid containing a column for displaying countrynames. I need to display value in that column as contrycode-first 10 letters of country name (in-India) .I tried it using Eval functions with in the item template:
我有一个包含用于显示国家/地区名称的列的网格。我需要将该列中的值显示为国家名称的 contrycode-first 10 个字母(在印度)。我在项目模板中使用 Eval 函数进行了尝试:
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="CountryNameLabe" runat="server" Text='<%# Eval("CorporateAddressCountry").SubString(0,6) %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
But it shows error. Can i use custom functions in eval? please help
但它显示错误。我可以在 eval 中使用自定义函数吗?请帮忙
采纳答案by Tim Schmelter
You can use the ternary operator ?:
您可以使用三元运算符?:
<asp:Label ID="CountryNameLabel" runat="server"
Text='<%# Eval("CorporateAddressCountry").ToString().Length <= 10 ? Eval("CorporateAddressCountry") : Eval("CorporateAddressCountry").ToString().Substring(0,10) %>' >
</asp:Label>
Another, in my opinion more readable, way is to use GridView's RowDataBoundevent:
在我看来,另一种更具可读性的方法是使用 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);
}
}
回答by Rn.
I did it using
我用
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);
}

