【问题标题】:Passing variables to usercontrol inside the listview (asp.net, c#)将变量传递给列表视图中的用户控件(asp.net,c#)
【发布时间】:2017-09-11 22:17:14
【问题描述】:

我想将一些动态信息从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 获取值时,usercontrol 中的字符串值为“null” 谁能看到我做错了什么?谢谢,吉姆·奥克

【问题讨论】:

  • 谢谢。我遇到了完全相同的问题。

标签: c# asp.net listview user-controls


【解决方案1】:

DataBinding 在控件生命周期中发生的时间比Load 晚很多。

您在 Load 上分配文本,但您的控件仅在 DataBind 上接收文本

要解决此问题,您可以将文本设置为 OnPreRender。这发生在DataBind

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

【讨论】:

  • 我也遇到了同样的问题。谢谢!
【解决方案2】:

您的代码中的一切看起来都很好,只需检查代码行:

<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" />

【讨论】:

  • 嗨,对不起,我在创建这个主题时做了这个。
  • 你检查过aspx代码隐藏文件中的数据源吗?结果集有这些字段“名称”和“描述”的值?
  • 是的,如果我将 .ascx 代码粘贴到 itemtemplate 中,一切正常。我想我在将变量传递给用户控件时遗漏了一些东西。
猜你喜欢
  • 2010-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-23
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 1970-01-01
相关资源
最近更新 更多