Monday, March 26, 2012

Pass value to Web User Control

Say I have a user control like this one...
private Sections s = new Sections();

private void Page_Load(object sender, System.EventArgs e)
{
}

public Sections Sections
{
get { return s; }
set { s = value; }
}

public void f()
{
if (s.Query.Load())
while (s.MoveNext())
Response.Write(string.Format("<tr><td width='5'><img src='images/arrow.gif'></td><td><a href='showsections.aspx?s={0}'>{1}</a></td></tr>", s.SectionId, s.Title));
}
And I dragged the user control to index.aspx. Now, on page load of index.aspx, I want to pass some value to the user control's Section property. How do I do this? Or is this possible?

Thanks.If you have the User Control on the Page then you can simply use myUserControl.Sections = someValue; This is same as you would do for any other control on your page.
The thing is, even if i dragged the UserControl on my index.aspx, I can't seem to find SectionsControl (my web user control). At design mode though, I can see SectionsControl1 on index.aspx.

Am I missing something here?
Yes that is pretty much the behaviour you expect for any other control you add to a page. When you add a textbox control first time, the name of textbox will be textBox1 and second control will the name textBox2. In the same manner when you add a usercontrol, it will also follow the same behaviour. So in your code you should write this SectionsControl1.Sections = someValue;
It's a bug in VS 2003. You add a control to your page, but it fails to show up in your codebehind.

Go into the codebehind designer region, and declare your control (of the same name as on the page) with events.
Or, when you add your control to your page by dragging, save your page, THEN go into codebehind. It should show up there.
I missed this post last days. Sorry for the late reply. A bug that is, so decided to declare it myself. Thanks guys.

0 comments:

Post a Comment