473,503 Members | 1,804 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamic web controls

6 New Member
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.
May 26 '09 #1
8 1789
Frinavale
9,735 Recognized Expert Moderator Expert
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.
May 26 '09 #2
pisgasys
6 New Member
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.
May 27 '09 #3
pisgasys
6 New Member
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!
May 27 '09 #4
Frinavale
9,735 Recognized Expert Moderator Expert
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?
May 27 '09 #5
pisgasys
6 New Member
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
May 27 '09 #6
Frinavale
9,735 Recognized Expert Moderator Expert
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. }
May 27 '09 #7
pisgasys
6 New Member
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.
May 28 '09 #8
Frinavale
9,735 Recognized Expert Moderator Expert
@pisgasys
I'm glad you got it working :)
May 28 '09 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

1
6308
by: Will | last post by:
Hi all. I'm learning VB.Net and am developing a WinForms app. I'm trying to make an app that I will use to scan in one or more than on image. I want to use a tabbed interface to hold each image....
2
5296
by: theComputer7 | last post by:
I cut down the code to make this half way understandable... I have read Data Grid girls caution about over use of dynamic controls. I truly believe what I am doing requires dynamically inserted...
1
1988
by: hybrid | last post by:
I have problems in understanding the behavior of the events triggered by dynamically created controls over a webform. Could you help me? In a webform, I have a static PlaceHolder PH containing...
2
2541
by: Dave Williamson | last post by:
When a ASPX page is created with dynamic controls based on what the user is doing the programmer must recreate the dynamic controls again on PostBack in the Page_Load so that it's events are wired...
3
3946
by: Leo J. Hart IV | last post by:
OK, here's another question for the experts: I am building a multi-step (3 steps actually) form using a panel for each step and hiding/displaying the appropriate panel/panels depending on which...
5
2388
by: mytestemailaccount | last post by:
Hi, Hope you can help. I am relatively new to all this but would appreciate the groups help. The scenario: I am c# and asp.net to create a web application. The web page contains a user...
1
1910
by: pbb | last post by:
I'm creating a set of dynamic controls on a webpage by calling my BuildControls sub in the Page_Init sub. I recreate the controls by calling the BuildControls sub in the LoadViewState override...
3
1843
by: WebBuilder451 | last post by:
I have a series of dynamic link buttons created based upon a datareader. I've added a click event and it calls the sub ok: example: "while loop through the reader" Dim ltrCtrl As New...
1
2170
by: Diffident | last post by:
Hello All, I am trying to add dynamic controls onto my page and here is how I am doing that. I have a page which has a button called as "AddMoreControls" and in this button's event handler I...
9
3608
by: Tarscher | last post by:
hi all, I have this seemingly simple problem. I have lost a lot of time on it though. When a user selects a value from a dropdownlist (static control) a dynamic control is generated. I have...
0
7199
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7076
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
6984
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5576
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4670
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3162
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3151
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1507
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
377
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.