27

I haven't used these in awhile. I was just wondering is it possible to pass values or parameters to a user control from the aspx page. Say you register a control and then use it using something like

<uc1:SampleUserControl id="SampleUserControl1" runat="server"></uc1:SampleUserControl>

style syntax. Can you pass parameters in there?

Josh M.
  • 26,437
  • 24
  • 119
  • 200
chobo
  • 31,561
  • 38
  • 123
  • 191
  • I found that it was necessary to set the CodeBehind property in the .ascx file to the associated ascx.cs/ascx.vb file – andrewb Feb 03 '15 at 22:13

2 Answers2

47

Yes:

<my:Control runat="server" MyPublicProperty="Value1" MyPublicProperty2="Value2"/>

Any public property can be set in the markup as indicated above. You can get more advanced than this and support child elements, etc. too. See more information.

Josh M.
  • 26,437
  • 24
  • 119
  • 200
  • 4
    Another approach is add `Control.MyPublicProperty = "Value1";` inside the Page_Load on the `.cs` file. – RaphaelDDL May 06 '13 at 17:05
  • 1
    @RaphaelDDL Yes, but in general it is preferred to do what you can in the markup. If you have to do something complex, then it goes in the code-behind. If you can do it in the markup easily, then do it there. Even better - switch to MVC and stop using server controls! ;) – Josh M. Apr 21 '15 at 13:19
4

Create public properties in the code behind of the user control and then these could be used as attributes while declaring the user control in the page. Check here

amit_g
  • 30,880
  • 8
  • 61
  • 118