c# - 模板中的服务器控件如何对数据上下文敏感?

标签 c# .net asp.net data-binding templates

假设控件 X 有一个名为 RowTemplate 的模板.

所以 X 的标记应该是这样的:

<foo:X>
    <RowTemplate>
        <foo:Y>...</foo:Y>
    </RowTemplate>
</foo:X>

我的问题是:Y 控件如何对数据上下文敏感?我知道我可以使用模板内联标签来访问数据上下文:<%# Eval("Id") %> , 但我无法将此信息传递给 Y,因为服务器控件中不允许使用模板内联标记。

所以我不知道如何在 Y 中使用对象的 Id (Eval("Id"))。

最佳答案

通过向 ItemDataBound 事件(或 foo:X 控件上的其他类似事件)添加处理程序,您可以访问行模板中的控件。我的示例代码来自 DataList,因此您的事件处理程序可能会有所不同。

在后面的代码中 - 连接事件处理程序:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);

    foo.ItemDataBound += new DataListItemEventHandler(foo_ItemDataBound);
}

然后在事件处理程序中,访问您所在行中的控件。您的数据可能不是 DataRow,因此请根据需要进行更改。

void foo_ItemDataBound(object sender, DataListItemEventArgs e)
{
    Control fooY = (e.Item.FindControl("foo:Y") as Control); //Replace foo:Y with the ID for foo:Y
    DataRow data = e.Item.DataItem as DataRow;
    fooY.SomeProperty = data["id"];
}

关于c# - 模板中的服务器控件如何对数据上下文敏感?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2136517/

相关文章:

c# - 在mysql中使用scope_identity()、@@identity()、last_insert_id()的正确版本是什么

c# - 条件运算符和比较委托(delegate)

c# - 按颜色为条码位图着色

c# - 优雅地停止 .net 启动的 Java 进程

c# - CSharpCodeProvider 设置编译细节

c# - 使用 asp.net mvc 进行依赖注入(inject)

c# - 存储过程未在表中插入值

c# - 移动到另一个项目时无法识别类型化数据集

c# - 使用 Func Delegate 进行错误检查

c# - 如何在 Blazor 服务器端注销?