Connecting Tech Pros Worldwide Forums | Help | Site Map

Dynamic web controls

Newbie
 
Join Date: May 2009
Posts: 6
#1: May 26 '09
Hi,

in my aspx page I have somting like that:
Expand|Select|Wrap|Line Numbers
  1. <asp:Content ID="Content1" ContentPlaceHolderID="Body" Runat="Server">
  2.     <asp:UpdatePanel ID="UpdatePanel1" ChildrenAsTriggers="true" UpdateMode="Conditional" runat="server" >
  3.         <ContentTemplate>
  4.             <asp:Panel ID="Panel1" runat="server">
  5.  
  6. <asp:Table ID="PO_Tags" Width="90%" BorderWidth="1" HorizontalAlign="Center" 
  7.                 CellPadding ="2" CellSpacing ="1" visible="false" runat="server">
  8.                 <asp:TableHeaderRow>
  9.                     <asp:TableHeaderCell BackColor="AliceBlue" >Tag Name<br /><br /></asp:TableHeaderCell>
  10.                     <asp:TableHeaderCell BackColor="AliceBlue" >Association Type<br /><br /></asp:TableHeaderCell>
  11.                     <asp:TableHeaderCell BackColor="AliceBlue" >Tag Description<br /><br /></asp:TableHeaderCell>
  12.                     <asp:TableHeaderCell BackColor="AliceBlue" >Tag Value<br /><br /></asp:TableHeaderCell>
  13.                 </asp:TableHeaderRow>
  14.             </asp:Table>
  15.  
  16.             <br />
  17.             <asp:Button ID="Submit" Text="Submit" OnClick="Submit_Click" Visible="false" runat="server" />
  18.  
  19.             </asp:Panel>
  20.         </ContentTemplate>
  21.      </asp:UpdatePanel> 
  22. </asp:Content>
from c# code I'm building my table rows dynamicly:
Expand|Select|Wrap|Line Numbers
  1. while (rdr.Read())
  2.                     {
  3.                         trRow = new TableRow();
  4.  
  5.                         tcCell = new TableCell();
  6.                         tcCell.Text = rdr["Label"].ToString();
  7.                         trRow.Cells.Add(tcCell);
  8.  
  9.                         tcCell = new TableCell();
  10.                         switch (rdr["ControlType"].ToString())
  11.                         {
  12.                             case "Text":
  13.                             case "Integer":
  14.                             case "Real":
  15.                                 TextBox ctrl1 = new TextBox();
  16.                                 ctrl1.ID = String.Format("tagCtrl{0}" ,countTagsControls);
  17.                                 ctrl1.Text = "Test";
  18.                                 tcCell.Controls.Add(ctrl1);
  19.                                 //this.UpdatePanel1.ContentTemplateContainer.Controls.Add(ctrl1);
  20.                                 break;
  21.  
  22.                               .......
  23.  
  24.                      }
  25.  
  26.            trRow.Cells.Add(tcCell);
  27.            PO_Tags.Rows.Add(trRow);
Then I'm trying to get the values of those controls:
Expand|Select|Wrap|Line Numbers
  1. TextBox txtCtl = (TextBox)UpdatePanel1.FindControl(String.Format("tagCtrl{0}", i));
  2.                     switch (rdr["ControlType"].ToString())
  3.                     {
  4.                         case "Text":
  5.                             string v1 = txtCtl.Text.ToString();
  6.                             break;
  7.  
But it's not working!!
What I'm missing?!

Thanks in advance.

Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North
Posts: 5,719
#2: May 26 '09

re: Dynamic web controls


You need to specify what isn't working.
But I think I know what's wrong.
You aren't able to find the TextBox are you?

Well, that's because you declared the TextBoxes dynamically within the function that creates the DataTable. That means that these TextBoxes have a scope of that function...they no longer exist after the function is finished.

Before I continue you need to specify what your problem is.
Check out this article on How to use dynamic controls in ASP.NET

Also research using Templates.
Newbie
 
Join Date: May 2009
Posts: 6
#3: May 27 '09

re: Dynamic web controls


Hi again,
Well the problem is here:
Expand|Select|Wrap|Line Numbers
  1. TextBox txtCtl = (TextBox)UpdatePanel1.FindControl(String.format("tagCtrl{0}", i));
  2. string v1 = txtCtl.Text.ToString();
The controls are created, but I'm not succeeding to get there values, If I'm trying to retrieve:
Expand|Select|Wrap|Line Numbers
  1.  UpdatePanel1.FindControl(String.format("tagCtrl{0}", i)).ID
I'm getting null!

I tried declaring my textbox ctrl1 outside the function as public but I'm still facing the same issue!

I'll research about Templates, thanks.
If you have any other ideas please let me know.
Newbie
 
Join Date: May 2009
Posts: 6
#4: May 27 '09

re: Dynamic web controls


When I put my code of building dynamic controls inside page_load it worked fine, but I need to run that code from another function, so I tried:
Expand|Select|Wrap|Line Numbers
  1. public partial class PO_Insert : System.Web.UI.Page
  2.     {
  3.  
  4.         public TextBox ctrl1 = null;
  5.         public TableRow trRow = null;
  6.         public TableCell tcCell = null;
  7.  
but still have a problem!
Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North
Posts: 5,719
#5: May 27 '09

re: Dynamic web controls


You should be creating your new TextBox in the Page Init event (not the Page Load) or else you wont be able to retrieve the content from the dynamically created TextBox.

You need to retrieve your TextBox from the control that it exists within....in this case it's part of the Table control (not the UpdatePanel).

Don't you need more than one TextBox in your table?
How many TextBoxes do you need?
I still don't know what you're trying to do....

Is the column displaying the "Association Type" (the "ControlType") supposed to be displaying data in TextBoxes for all rows?
Newbie
 
Join Date: May 2009
Posts: 6
#6: May 27 '09

re: Dynamic web controls


Hi,
The number of my controls is changing dynamically according to association mechanism (I'm taking part of developing of system that simulating XFactory if you know it) .
Those controls can be TextBoxes or CheckBoxes or ComboBoxes .. according to a controlType field stored in the db.
So what I'm trying to do is:

1) Fill a form with new production order for a factory (Line, CatalogID,...)
2) Retrieve the Tags that are relevant to that PO
3) Building the controls dynamically according to the tags hierarchy
4) Filling values into those controls (manually) and submitting
5) Build an XML file with those values
6) Send that xml to a stored procedure that verify the data and it types (Via web service)
7) Inserting that data into my tables if every thing is ok
Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North
Posts: 5,719
#7: May 27 '09

re: Dynamic web controls


Ok, this is going to be a tricky one to implement.

I'm not entirely sure how you're going to do this... or even if what I'm about to recommend is going work.

I think you're going to have to do is create something to hold the dynamically created controls so that you can reference it later.

I'm going to recommend creating a generic List of Web.UI.Control types:

Expand|Select|Wrap|Line Numbers
  1. public partial class PO_Insert : System.Web.UI.Page
  2. {
  3.   List<Web.UI.Control> webControlContent;
  4. }
Now in your Page Init event you're going to have poll the database in order to dynamically create your controls. Each control that you create you're going to have add to the the generic list and to your page.

For now let's forget the Table all together.
Let's just add the controls as one big mess to the page as we create them.

So in the method that handles the Page Init class you'll have something like:

Expand|Select|Wrap|Line Numbers
  1. public partial class PO_Insert : System.Web.UI.Page
  2. {
  3.   List<Web.UI.Control> webControlContent;
  4.  
  5.   private void PO_Insert_Init(Object sender, System.EventArgs e)
  6.   {  
  7.      //Initializing the generic list of web controls
  8.      webControlContent = new List<Web.UI.Control>();
  9.  
  10.      /*
  11.       Now you need to call the database to figure out 
  12.        what type of controls to create.
  13.  
  14.        You should look into using Reflection to make this
  15.        process easier and cleaner.
  16.     */
  17.  
  18.      /*
  19.       Add the controls to the webControlContent list and 
  20.       also add them Page.
  21.  
  22.       Make sure to give the controls an ID so that 
  23.       you can access them later.
  24.  
  25.        You also need to specify any methods used to handle
  26.        any postback events that the controls may cause.
  27.     */
  28.  
  29.  
  30.   }
  31.  
  32. }
You always need to recreate the controls used on the page in the Page Init event.

After the Page Init event they are loaded with the data that was entered by the user. If the control does not exists when ASP.NET is trying to load the data you are going to have problems.

Now that you have your controls available for you to use you can use them:

Expand|Select|Wrap|Line Numbers
  1. string v1 = "";
  2. foreach (Web.UI.Control ctrl in webControlContent )
  3. {
  4.     if(ctrl.ID == "txtCtrl")
  5.     {
  6.       TextBox txtCtl = (TextBox) ctrl;
  7.       v1 = txtCtl.Text;
  8.     }
  9. }
Newbie
 
Join Date: May 2009
Posts: 6
#8: May 28 '09

re: Dynamic web controls


That's what I did, and it works:

Expand|Select|Wrap|Line Numbers
  1. protected void Page_PreLoad(object sender, EventArgs e)
  2.         {
  3.             SqlConnection conn = null;
  4.             SqlCommand cmd = null;
  5.             SqlDataReader rdr = null;
  6.             int i = 0;
  7.  
  8.             conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
  9.             if (ViewState["isTextBoxCreated"] != null && (int)ViewState["isTextBoxCreated"] == 1) 
  10.             {
  11.                 try
  12.                 {
  13.                     TableRow trRow = null;
  14.                     TableCell tcCell = null;
  15.  
  16.                     conn = new SqlConnection(conString);
  17.                     conn.Open();
  18.  
  19.                     cmd = new SqlCommand("sp_BuildPODataTags", conn);
  20.                     cmd.CommandType = CommandType.StoredProcedure;
  21.  
  22.                     cmd.Parameters.Add(new SqlParameter("@POID", txtPOID.Text));
  23.                     cmd.Parameters.Add(new SqlParameter("@LineUID", lstLines.SelectedValue.ToString()));
  24.  
  25.                     rdr = cmd.ExecuteReader();
  26.  
  27.                     while (rdr.Read())
  28.                     {
  29.                         trRow = new TableRow();
  30.  
  31.                         tcCell = new TableCell();
  32.                         tcCell.Text = rdr["Label"].ToString();
  33.                         trRow.Cells.Add(tcCell);
  34.  
  35.                         tcCell = new TableCell();
  36.                         if (Convert.ToInt16(rdr["AssociationType"]) == 100)
  37.                             tcCell.Text = "Global";
  38.                         else
  39.                             tcCell.Text = "Line";
  40.                         trRow.Cells.Add(tcCell);
  41.  
  42.                         tcCell = new TableCell();
  43.                         tcCell.Text = rdr["Description"].ToString();
  44.                         trRow.Cells.Add(tcCell);
  45.  
  46.                         tcCell = new TableCell();
  47.                         switch (rdr["ControlType"].ToString())
  48.                         {
  49.                             case "Text":
  50.                             case "Integer":
  51.                             case "Real":
  52.                                 TextBox ctrl1 = new TextBox();
  53.                                 ctrl1.ID = "tagCtrl" + i.ToString();
  54.                                 tcCell.Controls.Add(ctrl1);
  55.                                 break;
  56.                             case "Combo Box":
  57.                                 break;
  58.                             case "Check Box":
  59.                                 break;
  60.                         }
  61.                         i += 1;
  62.  
  63.                         trRow.Cells.Add(tcCell);
  64.                         PO_Tags.Rows.Add(trRow);
  65.  
  66.                     }
  67.  
  68.                 }
  69.  
  70.                 finally
  71.                 {
  72.                     if (conn != null)
  73.                     {
  74.                         conn.Close();
  75.                     }
  76.                     if (rdr != null)
  77.                     {
  78.                         rdr.Close();
  79.                     }
  80.                 }
  81.             }
  82.         }
  83.  
  84.  
  85.          protected void GetTags_Click(object sender, EventArgs e)
  86.          {
  87.             if (Validate_Data())
  88.             {
  89.                 SqlConnection conn = null;
  90.                 SqlCommand cmd = null;
  91.                 SqlDataReader rdr = null;
  92.                 int countTagsControls = 0;
  93.  
  94.                 this.UpdatePanel1.FindControl("PO_Tags").Visible = true;
  95.                 this.Submit.Visible = true;
  96.  
  97.                 //Create_XML();
  98.                 if (ViewState["isTextBoxCreated"] == null)
  99.                 {
  100.  
  101.                     try
  102.                     {
  103.                         TableRow trRow = null;
  104.                         TableCell tcCell = null;
  105.  
  106.                         conn = new SqlConnection(conString);
  107.                         conn.Open();
  108.  
  109.                         cmd = new SqlCommand("sp_BuildPODataTags", conn);
  110.                         cmd.CommandType = CommandType.StoredProcedure;
  111.  
  112.                         cmd.Parameters.Add(new SqlParameter("@POID", txtPOID.Text));
  113.                         cmd.Parameters.Add(new SqlParameter("@LineUID", lstLines.SelectedValue.ToString()));
  114.  
  115.                         rdr = cmd.ExecuteReader();
  116.                         while (rdr.Read())
  117.                         {
  118.                             trRow = new TableRow();
  119.  
  120.                             tcCell = new TableCell();
  121.                             tcCell.Text = rdr["Label"].ToString();
  122.                             trRow.Cells.Add(tcCell);
  123.  
  124.                             tcCell = new TableCell();
  125.                             if (Convert.ToInt16(rdr["AssociationType"]) == 100)
  126.                                 tcCell.Text = "Global";
  127.                             else
  128.                                 tcCell.Text = "Line";
  129.                             trRow.Cells.Add(tcCell);
  130.  
  131.                             tcCell = new TableCell();
  132.                             tcCell.Text = rdr["Description"].ToString();
  133.                             trRow.Cells.Add(tcCell);
  134.  
  135.                             tcCell = new TableCell();
  136.                             switch (rdr["ControlType"].ToString())
  137.                             {
  138.                                 case "Text":
  139.                                 case "Integer":
  140.                                 case "Real":
  141.                                     TextBox ctrl1 = new TextBox();
  142.                                     ctrl1.ID = "tagCtrl" + countTagsControls.ToString();
  143.                                     ctrl1.Text = rdr["Value"].ToString ();
  144.                                     tcCell.Controls.Add(ctrl1);
  145.                                     ViewState["isTextBoxCreated"] = 1;
  146.                                     break;
  147.                                 case "Combo Box":
  148.                                     break;
  149.                                 case "Check Box":
  150.                                     break;
  151.                             }
  152.                             countTagsControls += 1;
  153.  
  154.                             trRow.Cells.Add(tcCell);
  155.                             PO_Tags.Rows.Add(trRow);
  156.  
  157.                         }
  158.                     }
  159.  
  160.                     finally
  161.                     {
  162.                         if (conn != null)
  163.                         {
  164.                             conn.Close();
  165.                         }
  166.                         if (rdr != null)
  167.                         {
  168.                             rdr.Close();
  169.                         }
  170.                     }
  171.                 }
  172.             }
  173.  
  174.         }
  175.  
  176.         public void Create_XML()
  177.         {
  178.             SqlConnection conn = null;
  179.             SqlCommand cmd = null;
  180.             SqlDataReader rdr = null;
  181.  
  182.             // Create a new XmlTextWriter instance
  183.             writer = new XmlTextWriter(Server.MapPath(@"XML\POInfo.xml"), Encoding.UTF8);
  184.  
  185.             // Creating <POInfo> element
  186.             writer.WriteStartDocument();
  187.             writer.WriteStartElement("POInfo");
  188.  
  189.             // Creating the <PO> element
  190.             writer.WriteStartElement("PO");
  191.  
  192.             writer.WriteElementString("POID", txtPOID.Text);
  193.             writer.WriteElementString("LineID", lstLines.SelectedItem.ToString());
  194.             writer.WriteElementString("CatalogID", lstCatalogs.SelectedValue.ToString());
  195.             writer.WriteElementString("RequestedQty", txtRequestedQty1.Text + "." + txtRequestedQty2.Text);
  196.             writer.WriteElementString("LotID", txtLotID.Text);
  197.             writer.WriteElementString("Priority", txtPriority.Text);
  198.             writer.WriteElementString("UserID", Session["User"].ToString());
  199.  
  200.             writer.WriteEndElement();
  201.             //  </PO>
  202.  
  203.             // Creating <POTags> element
  204.             writer.WriteStartElement("POTags");
  205.             try
  206.             {
  207.                 conn = new SqlConnection(conString);
  208.                 conn.Open();
  209.  
  210.                 cmd = new SqlCommand("sp_BuildPODataTags", conn);
  211.                 cmd.CommandType = CommandType.StoredProcedure;
  212.  
  213.                 cmd.Parameters.Add(new SqlParameter("@POID", txtPOID.Text));
  214.                 cmd.Parameters.Add(new SqlParameter("@LineUID", lstLines.SelectedValue.ToString()));
  215.  
  216.                 rdr = cmd.ExecuteReader();
  217.  
  218.                 int i = 0;
  219.                 String ctlValue = "";
  220.                 while (rdr.Read())
  221.                 {
  222.                     switch (rdr["ControlType"].ToString())
  223.                     {
  224.                         case "Text":
  225.                         case "Real":
  226.                         case "Integer":
  227.                             TextBox txtCtl = (TextBox)UpdatePanel1.FindControl("tagCtrl" + i);
  228.                             ctlValue = txtCtl.Text.ToString();
  229.                             break;
  230.                     }
  231.                     i += 1;
  232.  
  233.                     writer.WriteStartElement("Tag");
  234.                     writer.WriteAttributeString("ID", rdr["TagDefId"].ToString());
  235.                     writer.WriteElementString("Value", ctlValue);
  236.                     writer.WriteEndElement();
  237.                 }
  238.             }
  239.             finally
  240.             {
  241.                 if (conn != null)
  242.                     conn.Close();
  243.                 if (rdr != null)
  244.                     rdr.Close();
  245.             }
  246.             writer.WriteEndElement();
  247.             //  </POTags>
  248.  
  249.             writer.WriteEndElement();
  250.             writer.WriteEndDocument();
  251.             writer.Close();
  252.             //  </POInfo>
  253.         }
  254.  
Thanks for your efforts.
Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North
Posts: 5,719
#9: May 28 '09

re: Dynamic web controls


Quote:

Originally Posted by pisgasys View Post

That's what I did, and it works:
...
Thanks for your efforts.

I'm glad you got it working :)
Reply