Gib*_*boK 5 c# asp.net repeater anonymous-types
我使用C#asp.net4.
我有一个方法来填充带有匿名类型的Repeater(Fields:Title,CategoryId),在Repeater中我还放置了一个Label:
var parentCategories = from c in context.CmsCategories
where c.CategoryNodeLevel == 1
select new { c.Title, c.CategoryId };
uxRepeter.DataSource = parentCategories;
uxRepeter.DataBind();
Run Code Online (Sandbox Code Playgroud)
我需要在Repeater事件ItemDataBound上更改Repeater中的每个标签的Text Properties
protected void uxRepeter_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
HyperLink link = (HyperLink)e.Item.FindControl("uxLabel");
uxLabel.Text = // How to do here!!!!!!!!
}
Run Code Online (Sandbox Code Playgroud)
所以我需要使用e.Item设置Label.Text的属性(或者更好的方法).
我的问题我无法使用e.Item(匿名类型字段标题)并将其设置为我的标签的Text Propriety.
我知道匿名类型只能被转换为对象类型,但在我的情况下,我的匿名类型有标题和CategoryId字段.
我的问题:
如何投射和检索我感兴趣的领域?谢谢你的时间吗?
编辑:我收到的一些错误:
Unable to cast object of type '<>f__AnonymousType0`2[System.String,System.Int32]' to type 'System.String'.
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 10
选项约瑟夫的礼物是好的,但也有是你可以做这个可怕的方式.它有点脆弱,因为它依赖于你在两个地方以完全相同的方式指定匿名类型.开始了:
public static T CastByExample<T>(object input, T example)
{
return (T) input;
}
Run Code Online (Sandbox Code Playgroud)
然后:
object item = ...; // However you get the value from the control
// Specify the "example" using the same property names, types and order
// as elsewhere.
var cast = CastByExample(item, new { Title = default(string),
CategoryId = default(int) } );
var result = cast.Title;
Run Code Online (Sandbox Code Playgroud)
编辑:进一步皱纹 - 两个匿名类型创建表达式必须在同一个程序集(项目)中.很抱歉忘记在此之前提及.
| 归档时间: |
|
| 查看次数: |
10218 次 |
| 最近记录: |