Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

reference a control that has been dynamically created

Posted on 2011-03-19
8
435 Views
Last Modified: 2012-05-11
I have a web project created with vs2008 and .net 3.5.  I have created a radiobuttonlist control in a table cell dynamically by adding the control to the tablecell.controls collection.  The problem is that I can't retrieve this control from code behind on a button click, the tablecell.controls collection returns 0 as the count.

How can I do this?  I need to read the radiobuttonlist selection to perform an action.
0
Comment
Question by:dhenderson12
8 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 125 total points
ID: 35174206
When/where are you adding the controls? Load, PreInit, PreRender, etc.
0
 
LVL 35

Assisted Solution

by:Miguel Oz
Miguel Oz earned 250 total points
ID: 35174285
Where are you keeping your control's state?
Without it, your table cannot remember the dynamic controls when you postback the page (button click)

For state implementation, check:
http://www.codeproject.com/KB/aspnet/state_management_intro.aspx
http://msdn.microsoft.com/en-us/library/75x4ha6s.aspx
0
 
LVL 29

Assisted Solution

by:anarki_jimbel
anarki_jimbel earned 125 total points
ID: 35177071
I believe the easiest way is to have a declaration for a control of this type on a, say, class level, something like:

RadioButtonList rbl = null;

In some method call you create a new RadioButtonList object and add it to a cell. You may create it like:

rbl = new RadioButtonList();...
// do all stuff to fill it etc


Now you may check anywhere in your code that if( rbl!=null) you can do something with it.

Should be pretty simple.

In some more complex cases when you need to create a number of similar controls (and you don't know how many in advance)  you may add them, say, to a Dictionary or to a List etc.

0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:dhenderson12
ID: 35184606
Sorry, all, seems I didn't provide enough information.  This is a content page that is using a master page.  I have a function called loadPage() that is called from a button click.  The control is defined in an xml file, along with the options:
      <control name="OptionList" type="radio">
         <options>
            <option text="Option1" code="OPT1" />
            <option text="Option2" code="OPT2" />
            <option text="Option3" code="OPT3" />
            <option text="Option4" code="OPT4" />
            <option text="Option5" code="OPT5" />
         </options>
      </control>


Here is the code that write the control on the page:
                  switch (controlType.Value)
                  {
                     case "radio":
                        rl = new RadioButtonList();
                        rl.ID = controlName.Value;
                       
                        rl.SelectedIndexChanged += new EventHandler(rlb_SelectedIndexChanged);


                        var options = item.XPathSelectElement("options");

                        foreach (XElement opt in options.Elements())
                           rl.Items.Add(new ListItem(opt.Attribute("text").Value, opt.Attribute("code").Value));


                        tr = TableSurvey.Rows[2];
                        tc = tr.Cells[0];
                        tc.Text = "Please select an option";

                        tc = tr.Cells[2];
                        tc.Controls.Add(rl);
                        break;
                  }

This displays the control perfectly and the control works as expected, but no event fires and I don't know how to reference the control correctly to try to read it's selection.

I really appreciate you all taking a stab at this.
0
 

Author Comment

by:dhenderson12
ID: 35184616
Forgot to add the event code:
      private void rlb_SelectedIndexChanged(object sender, EventArgs e)
      {
         sOption = ((RadioButtonList) sender).SelectedValue;
      }

sOption is a class level string.
0
 
LVL 35

Assisted Solution

by:Miguel Oz
Miguel Oz earned 250 total points
ID: 35185011
How did you write your control on the page?
void page_load
{
  //code to write control
}

If this is the case then your rlb_SelectedIndexChanged will never contain your desired information because the code is rewriting the RadioButtonList (to default values) before the event is executed. Check page lifecycle:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
You have to review how you keep state in your page. Please post the complete code to provide more details if required.
0
 

Author Comment

by:dhenderson12
ID: 35185771

here is the code behind for the page.  it's only for a single page, so there's nothing missing.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml; //namespace to deal with XML documents
using System.Xml.Linq; //namespace to deal with LINQ to XML classes
using System.Xml.XPath;
using System.Xml.Serialization;
using System.IO;
using TMSSI.BipiDTC;
using System.Web.UI.HtmlControls;

namespace TMSSI.BipiDTC.Pradaxa.Branded
{
   public partial class branded : System.Web.UI.Page
   {
      private static string pageName = null;
      private string xmlTranslations = HttpContext.Current.ApplicationInstance.Server.MapPath("~/Translations.xml");
      private string xmlPages = HttpContext.Current.ApplicationInstance.Server.MapPath("~/WebPageDefinitions.xml");
      RadioButtonList rl = null;      
      private string sOption = null;
     
      protected void Page_Load(object sender, EventArgs e)
      {
         if (!IsPostBack)
         {
            pageName = "script";
            loadPage();
         }


      }

      protected void Button2_Click(object sender, EventArgs e)
      {
         fetchNextPage();
      }


      protected void Button1_Click(object sender, EventArgs e)
      {

      }



      private void fetchNextPage()
      {
         switch (pageName)
         {
            case "script":
               System.Diagnostics.Debug.WriteLine("Option: " + sOption);
               break;

         }



      }



      private void fetchLastPage()
      {

      }



      private void loadPage()
      {
         XElement xml = XElement.Load(xmlPages);
         foreach (XElement child in xml.Elements())
            System.Diagnostics.Debug.WriteLine(child);

         TableRow tr = null;
         TableCell tc = null;

         string val = "/webPage[@name='" + pageName + "']";

         var pages = xml.XPathSelectElements(val);
         foreach (XElement item in pages.Elements())
         {
            System.Diagnostics.Debug.WriteLine(item.Name.ToString());

            switch (item.Name.ToString())
            {
               case "formTitle":
                  XAttribute title = item.Attribute("title");

                  tr = TableSurvey.Rows[0];
                  tc = tr.Cells[0];
                  tc.Text = title.Value;

                  break;

               case "narration":
                  XAttribute loc = item.Attribute("location");
                  System.Diagnostics.Debug.WriteLine(loc.Value);
                  loc.Value += "/eng";

                  XElement trx = XElement.Load(xmlTranslations);
                  var xlat = trx.XPathSelectElement(loc.Value);

                  tr = TableNarration.Rows[0];
                  tc = tr.Cells[0];
                  tc.Text = xlat.Value;

                  break;

               case "control":
                  XAttribute controlType = item.Attribute("type");
                  XAttribute controlName = item.Attribute("name");

                  switch (controlType.Value)
                  {
                     case "radio":
                        rl = new RadioButtonList();
                        rl.ID = controlName.Value;
                       
                        rl.SelectedIndexChanged += new EventHandler(rlb_SelectedIndexChanged);


                        var options = item.XPathSelectElement("options");

                        foreach (XElement opt in options.Elements())
                           rl.Items.Add(new ListItem(opt.Attribute("text").Value, opt.Attribute("code").Value));


                        tr = TableSurvey.Rows[2];
                        tc = tr.Cells[0];
                        tc.Text = "Please select an option";

                        tc = tr.Cells[2];
                        tc.Controls.Add(rl);
                        //form1.Controls.Add(rl);
                        break;
                  }




                  break;

            }


         }




      }


      private void processPage()
      {

      }

      private void rlb_SelectedIndexChanged(object sender, EventArgs e)
      {
         sOption = ((RadioButtonList) sender).SelectedValue;

      }










   }
}
0
 

Author Closing Comment

by:dhenderson12
ID: 35185952
figured it out.  needed to put the code that draws the control in the page_load method.  

thanks to all of you for your help.
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Getting error in connectionstring with Excel. 30 45
VBScript on Html 15 47
JQuery Autocomplete Tag AJAX (Need nice script) 11 35
Unlocking a column in excel using C# 17 19
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

838 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question