将变量传递到ListView中的用户控件(ASP.NET,C#)

3
我希望能够将一些动态信息从listview传递到UserControl,但我猜我遗漏了什么。
.aspx页面:
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource"
        DataKeyNames="id_Image">
  <ItemTemplate>
       <uc1:Info Name_Lbl='<%# Bind("Name") %>'   Description_Lbl='<%# Bind("Description")%>' ID="info1"  runat="server" />
  </ItemTemplate>
</asp:ListView>

.ascx文件:

Name:
<asp:Label ID="NameLabel" runat="server"  />
Description:
<asp:Label ID="DescriptionLabel" runat="server"  />

.ascx后台代码文件:

public string Name_Lbl { get; set; }
public string Description_Lbl { get; set; }

protected void Page_Load(object sender, EventArgs e)
{  
    NameLabel.Text = Name_Lbl;
    DescriptionLabel.Text = Description_Lbl;  
}

如果我想从字符串文本中获取值,一切都正常:

<uc1:Info Name_Lbl="Name"   Description_Lbl="Description" ID="info1"  runat="server" />

但是当我尝试从Datasource获取值时,用户控件中的字符串值为"null"。有人能看出我做错了什么吗?谢谢,Jim Oak。


谢谢。我也遇到了完全相同的问题。 - Pitarou
2个回答

4

数据绑定(DataBinding)发生的时间比Load事件晚得多。

Load事件中分配文本,但是控件只会在DataBind事件中接收到文本。

为了解决这个问题,您可以在DataBind事件之后设置文本的值OnPreRender

protected override void OnPreRender(EventArgs e)
{  
    NameLabel.Text = Name_Lbl;
    DescriptionLabel.Text = Description_Lbl;  
}

1

你的代码看起来一切正常,只需检查代码行:

<uc1:Info Name_Lbl='<%# Bind("Name") %>'   Description_Lbl='<%# Bind("Description"%>' ID="info1"  runat="server" />

您缺少对Description_Lbl的右括号“)”。应该是:

<uc1:Info Name_Lbl='<%# Bind("Name") %>'   Description_Lbl='<%# Bind("Description")%>' ID="info1"  runat="server" />

抱歉,我在创建这个主题时犯了一个错误。 - Oak
你是否已经检查了后端代码中的数据源?结果集包含这些字段“姓名”和“描述”,它们的值是什么? - PM.
是的,如果我将 .ascx 代码粘贴到 ItemTemplate 中,一切都正常工作。我猜在将变量传递给用户控件时漏掉了某些东西。 - Oak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接