asp.net passing string variable to a user control

2019-05-23 18:21发布

问题:

I am trying to pass value of a code behind variable to a user control like:

<pv1:ShowPdf ID="ShowPdf2" runat="server" BorderStyle="Inset" BorderWidth="2px" FilePath='<%=path2%>'
        Height="700px" Width="856px" />

where path2 is a protected string variable declared in code behind. The problem is that the value of path2 is not being passed to the FilePath. What is the mistake I am making? Simply doing <%=path2%> gives me correct value of the path2 variable on the page. Any help will be most appreciated.

-- Ali

回答1:

Using <%= is the same as using Response.Write(string). This happens at a different point in the lifecycle than when your ShowPdf control is being built and properties being initialized - much later. Try instead using <%#, which sets the value during DataBind. You may need to call DataBind on your Page in CreateChildControls or some other method where path2 is being given a value.