3

I want to pass some dynamic information from the listview to UserControl, but I guess I'm missing something.

.aspx page:

<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 file:

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

.ascx codebehind file:

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;  
}

Everything is working fine if Im trying to get value from string text like:

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

But when I'm trying to get value from Datasource, the string values in usercontrol are "null" Can anyone see what I'm doing wrong? Thanks, Jim Oak

Oak
  • 1,159
  • 3
  • 13
  • 21

2 Answers2

4

DataBinding occurs a lot later in the Control Life cycle than Load.

You assign your text on Load, but your control only receives the text on DataBind

To fix this you can set your text OnPreRender. This occurs after DataBind

protected override void OnPreRender(EventArgs e)
{  
    NameLabel.Text = Name_Lbl;
    DescriptionLabel.Text = Description_Lbl;  
}
Benoit Kack
  • 3
  • 1
  • 3
nunespascal
  • 17,584
  • 2
  • 43
  • 46
1

Everything looks fine in your code just check the code line:

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

You are missing the closing bracket ")" against Description_Lbl. It should be:

<uc1:Info Name_Lbl='<%# Bind("Name") %>'   Description_Lbl='<%# Bind("Description")%>' ID="info1"  runat="server" />
PM.
  • 1,735
  • 1
  • 30
  • 38
  • Hi, sorry, i made this when i created this topic. – Oak Mar 13 '13 at 10:00
  • Have you checked the datasource in the aspx code behind file? Result set has these fields "Name" and "Description" with value? – PM. Mar 13 '13 at 10:06
  • Yes, if i paste the .ascx code in itemtemplate, everything is working fine. I guess im missing something when passing the variables to usercontrol. – Oak Mar 13 '13 at 10:10