Solved

Reading Dynamic controls like DropDownList in C#

Posted on 2007-11-21
3
6,649 Views
Last Modified: 2012-06-22
Hi,

I am working on C#, ASP.net 2.0

I have created a dynamic dropdown and added in the HTML Table and it displays fine with data.

In the form there is submit button.

on submit click I am not able to find the DropDownList, which I can see is there on the screen

Is there any another way to see the dynamic controls like DropDownList.

I also tried to see all the controls present from

string idIs = string.Empty;
foreach (Control c in pnlMain.Controls)
{
            idIs =  c.ID;
}

It gives me all null valuse

Why?? How can I get the values from dynamic controls

Here is mu code below:


On click on button



protected void btnSubmit_Click(object sender, EventArgs e)
{
        DropDownList SecurityQuestionDrp = (DropDownList)this.FindControl("SecurityQuestion"); // SecurityQuestion is the dynamic ID

        string strDrp = SecurityQuestionDrp.SelectedValue;
}



// Generates Dynamic dropdownlist and add to the html table DynamicTable after row 6

private void GetDynamicHTML()
    {
        oDynmcFld = new DynamicFieldBL();
        DataSet oDst = oDynmcFld.GetFieldsByFormId("GetFieldsByFormId", 1);
        oDst.Relations.Add("ControlValuesRelation", oDst.Tables[0].Columns["FieldId_PK"], oDst.Tables[1].Columns["FormFileds_Mstr_PK"]);
       
        DataTable oDt = oDst.Tables[0];

       HtmlTableRow htr = new HtmlTableRow();
       HtmlTableCell htc1 = new HtmlTableCell();
       HtmlTableCell htc2 = new HtmlTableCell();
       
       DropDownList drp = new DropDownList();
       
       int startWith = 6;        

        if (oDt.Rows.Count > 0)
        {
            for (int iCnt = 0; iCnt <= oDt.Rows.Count - 1; iCnt++)
            {
                htr = new HtmlTableRow();
                htc1 = new HtmlTableCell();
                htc2 = new HtmlTableCell();
               
                if (bool.Parse(oDt.Rows[iCnt]["IsMandatory"].ToString()))
                {
                    sTempHTML += "<font class=\"alert\">*</font> ";
                }

                if (oDt.Rows[iCnt]["FldType"].ToString() == "DropDownList")
                {
                    drp = new DropDownList();
                    drp.ID = oDt.Rows[iCnt]["FieldID"].ToString();
                    drp.Items.Clear();

                    DataTable dp = oDst.Tables[1];

                    foreach (DataRow da in dp.Rows)
                    {
                        if (oDt.Rows[iCnt]["FieldId_PK"].ToString() == da["FormFileds_Mstr_PK"].ToString())
                        {
                            drp.Items.Add(new ListItem(da["FieldValue"].ToString(), da["FieldValue"].ToString()));
                        }
                    }
                }                
               

                htr.Cells.Add(htc1);
                htr.Cells.Add(htc2);

                DynamicTable.Rows.Insert(startWith, htr);
                startWith = startWith + 1;
               
            }
        }
    }
   
   
   
    Some ASPX CODE
   
    <asp:Panel ID="pnlMain" runat="server" Width="100%">
          <table width="100%" cellpadding="3" cellspacing="0" border="0" id="DynamicTable" runat="server" >
                <tr>
                    <td colspan="2" class="alert">
                        <asp:Literal ID="lblMsgDisplay" runat="server" SkinID="lblErrSkin"></asp:Literal>
                            </td>
                </tr>
                <tr>
                    <td align="right">
                        <font class="alert">
                                        <asp:Literal runat="server" ID="litLoginMandatory2" Text="*"></asp:Literal>
                                  </font>
                        <asp:Literal ID="lblUserName" runat="server" Text="Username:"></asp:Literal></td>
                    <td align="left">
                        <asp:TextBox ID="txtUserName" runat="server" MaxLength="20"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RFVUserName" runat="server" ControlToValidate="txtUserName"
                            ErrorMessage="Please enter user name" SetFocusOnError="True" Display="None" ValidationGroup="vgOnlineUser"></asp:RequiredFieldValidator></td>
                </tr>
                <tr>
                    <td align="right">
                        <asp:Label ID="lblSalutation" runat="server" Text="Salutation:"></asp:Label></td>
                    <td align="left">
                        <asp:DropDownList ID="cmbSalutation" runat="server"></asp:DropDownList></td>
                </tr>
                <tr>
                    <td align="right">
                        <font class="alert">
                                        <asp:Literal runat="server" ID="litLoginMandatory" Text="*"></asp:Literal>
                                  </font>
                        <asp:Label ID="lblFirstName" runat="server" Text="First name:"></asp:Label></td>
                    <td align="left">
                        <asp:TextBox ID="txtFirstName" runat="server" MaxLength="50"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RFVFirstName" runat="server" ControlToValidate="txtFirstName" ErrorMessage="Please enter first name" SetFocusOnError="True" Display="None" ValidationGroup="vgOnlineUser"></asp:RequiredFieldValidator></td>
                </tr>
               
                <tr>
                    <td align="right">
                        <font class="alert">
                                        <asp:Literal runat="server" ID="litLoginMandatory3" Text="*"></asp:Literal>
                                  </font>
                        <asp:Label ID="lblSurname" runat="server" Text="Surname:"></asp:Label></td>
                    <td align="left">
                        <asp:TextBox ID="txtSurName" runat="server" MaxLength="50"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RFVSurname" runat="server" ControlToValidate="txtSurName"
                            ErrorMessage="Please enter your surname" SetFocusOnError="True" Display="None" ValidationGroup="vgOnlineUser"></asp:RequiredFieldValidator>
                        </td>
                </tr>
                <tr>
                    <td align="right">
                        <font class="alert">
                                        <asp:Literal runat="server" ID="litLoginMandatory4" Text="*"></asp:Literal>
                                  </font>
                        <asp:Label ID="lblEmail" runat="server" Text="Email:"></asp:Label></td>
                    <td align="left">
                        <asp:TextBox ID="txtEmail" runat="server" MaxLength="100"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RFVEmail" runat="server" ControlToValidate="txtEmail" ErrorMessage="Please enter email" SetFocusOnError="True" Display="None" ValidationGroup="vgOnlineUser"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="Rexpvemail" runat="server" ControlToValidate="txtEmail" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ErrorMessage="Invalid email (name@domain.com)" SetFocusOnError="True" Display="None" ValidationGroup="vgOnlineUser"></asp:RegularExpressionValidator>                </td>
                </tr>        
                                                       
                <tr >
                    <td>&nbsp;</td>
                        <td id="submitTD" runat="server">
                        <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" ValidationGroup="vgOnlineUser" Text="Apply" CssClass="formButtonFocus" />
                    <asp:Button ID="btnReset" OnClientClick="javascript:window.document.forms[0].reset(); return false;" runat="server" Text="Reset" CausesValidation="False" CssClass="formButton" />
                    <asp:ValidationSummary runat="server" ID="OnlineUserSummary" EnableClientScript="True"
                            ShowMessageBox="True" ShowSummary="False" validationgroup="vgOnlineUser"></asp:ValidationSummary>
                          <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
                      </td>
                </tr>
            </table>
    </asp:Panel>
On click on button 
 
 
 
protected void btnSubmit_Click(object sender, EventArgs e)
{
        DropDownList SecurityQuestionDrp = (DropDownList)this.FindControl("SecurityQuestion"); // SecurityQuestion is the dynamic ID
 
        string strDrp = SecurityQuestionDrp.SelectedValue;
}
 
 
 
// Generates Dynamic dropdownlist and add to the html table DynamicTable after row 6
 
private void GetDynamicHTML()
    {
        oDynmcFld = new DynamicFieldBL();
        DataSet oDst = oDynmcFld.GetFieldsByFormId("GetFieldsByFormId", 1);
        oDst.Relations.Add("ControlValuesRelation", oDst.Tables[0].Columns["FieldId_PK"], oDst.Tables[1].Columns["FormFileds_Mstr_PK"]);
        
        DataTable oDt = oDst.Tables[0];
 
       HtmlTableRow htr = new HtmlTableRow();
       HtmlTableCell htc1 = new HtmlTableCell();
       HtmlTableCell htc2 = new HtmlTableCell();
       
       DropDownList drp = new DropDownList();
       
       int startWith = 6;        
 
        if (oDt.Rows.Count > 0)
        {
            for (int iCnt = 0; iCnt <= oDt.Rows.Count - 1; iCnt++)
            {
                htr = new HtmlTableRow();
                htc1 = new HtmlTableCell();
                htc2 = new HtmlTableCell();
                
                if (bool.Parse(oDt.Rows[iCnt]["IsMandatory"].ToString()))
                {
                    sTempHTML += "<font class=\"alert\">*</font> ";
                }
 
                if (oDt.Rows[iCnt]["FldType"].ToString() == "DropDownList")
                {
                    drp = new DropDownList();
                    drp.ID = oDt.Rows[iCnt]["FieldID"].ToString();
                    drp.Items.Clear();
 
                    DataTable dp = oDst.Tables[1];
 
                    foreach (DataRow da in dp.Rows)
                    {
                        if (oDt.Rows[iCnt]["FieldId_PK"].ToString() == da["FormFileds_Mstr_PK"].ToString())
                        {
                            drp.Items.Add(new ListItem(da["FieldValue"].ToString(), da["FieldValue"].ToString()));
                        }
                    }
                }                
                
 
                htr.Cells.Add(htc1);
                htr.Cells.Add(htc2);
 
                DynamicTable.Rows.Insert(startWith, htr);
                startWith = startWith + 1;
                
            }
        }
    }
    
    
    
    Some ASPX CODE
    
    <asp:Panel ID="pnlMain" runat="server" Width="100%">
          <table width="100%" cellpadding="3" cellspacing="0" border="0" id="DynamicTable" runat="server" >
                <tr>
                    <td colspan="2" class="alert">
                        <asp:Literal ID="lblMsgDisplay" runat="server" SkinID="lblErrSkin"></asp:Literal>
    				</td>
                </tr>
                <tr>
                    <td align="right">
                        <font class="alert">
    						<asp:Literal runat="server" ID="litLoginMandatory2" Text="*"></asp:Literal>
    					</font>
                        <asp:Literal ID="lblUserName" runat="server" Text="Username:"></asp:Literal></td>
                    <td align="left">
                        <asp:TextBox ID="txtUserName" runat="server" MaxLength="20"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RFVUserName" runat="server" ControlToValidate="txtUserName"
                            ErrorMessage="Please enter user name" SetFocusOnError="True" Display="None" ValidationGroup="vgOnlineUser"></asp:RequiredFieldValidator></td>
                </tr>
                <tr>
                    <td align="right">
                        <asp:Label ID="lblSalutation" runat="server" Text="Salutation:"></asp:Label></td>
                    <td align="left">
                        <asp:DropDownList ID="cmbSalutation" runat="server"></asp:DropDownList></td>
                </tr>
                <tr>
                    <td align="right">
                        <font class="alert">
    						<asp:Literal runat="server" ID="litLoginMandatory" Text="*"></asp:Literal>
    					</font>
                        <asp:Label ID="lblFirstName" runat="server" Text="First name:"></asp:Label></td>
                    <td align="left">
                        <asp:TextBox ID="txtFirstName" runat="server" MaxLength="50"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RFVFirstName" runat="server" ControlToValidate="txtFirstName" ErrorMessage="Please enter first name" SetFocusOnError="True" Display="None" ValidationGroup="vgOnlineUser"></asp:RequiredFieldValidator></td>
                </tr>
                
                <tr>
                    <td align="right">
                        <font class="alert">
    						<asp:Literal runat="server" ID="litLoginMandatory3" Text="*"></asp:Literal>
    					</font>
                        <asp:Label ID="lblSurname" runat="server" Text="Surname:"></asp:Label></td>
                    <td align="left">
                        <asp:TextBox ID="txtSurName" runat="server" MaxLength="50"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RFVSurname" runat="server" ControlToValidate="txtSurName"
                            ErrorMessage="Please enter your surname" SetFocusOnError="True" Display="None" ValidationGroup="vgOnlineUser"></asp:RequiredFieldValidator>
                        </td>
                </tr>
                <tr>
                    <td align="right">
                        <font class="alert">
    						<asp:Literal runat="server" ID="litLoginMandatory4" Text="*"></asp:Literal>
    					</font>
                        <asp:Label ID="lblEmail" runat="server" Text="Email:"></asp:Label></td>
                    <td align="left">
                        <asp:TextBox ID="txtEmail" runat="server" MaxLength="100"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RFVEmail" runat="server" ControlToValidate="txtEmail" ErrorMessage="Please enter email" SetFocusOnError="True" Display="None" ValidationGroup="vgOnlineUser"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="Rexpvemail" runat="server" ControlToValidate="txtEmail" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ErrorMessage="Invalid email (name@domain.com)" SetFocusOnError="True" Display="None" ValidationGroup="vgOnlineUser"></asp:RegularExpressionValidator>                </td>
                </tr>        
                                                        
                <tr >
                    <td>&nbsp;</td>
                  	<td id="submitTD" runat="server">
                        <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" ValidationGroup="vgOnlineUser" Text="Apply" CssClass="formButtonFocus" />
                    <asp:Button ID="btnReset" OnClientClick="javascript:window.document.forms[0].reset(); return false;" runat="server" Text="Reset" CausesValidation="False" CssClass="formButton" />
                    <asp:ValidationSummary runat="server" ID="OnlineUserSummary" EnableClientScript="True"
                            ShowMessageBox="True" ShowSummary="False" validationgroup="vgOnlineUser"></asp:ValidationSummary>
                          <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
                      </td>
                </tr>
            </table>
    </asp:Panel>

Open in new window

0
Comment
Question by:tia_kamakshi
  • 2
3 Comments
 
LVL 33

Accepted Solution

by:
raterus earned 500 total points
ID: 20330170
Dynamic controls really suck, because you MUST recreate them on a postback in order to get the value out of them.  In other words, all the code you use to first add the controls must be reran each time you postback the page, if you want to interface with these controls, raise events, etc.
0
 

Author Comment

by:tia_kamakshi
ID: 20333472
Really goes over my head. Can you pls help me more in details.

If you ask me to re-create the dynamic controls on the postback then what about the values, which user has selected, that all will go away. Pls guide me, this is really urgent for me

Thanks
0
 

Author Comment

by:tia_kamakshi
ID: 20338315
I understood your point. Just recreated the html on postback and it works fine

MaAny Thanks
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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
How come this regular expression allows "e"? 14 45
asp.net mvc5 6 23
Need a simple RegEx to search for two words 27 46
How to filter by key press ? 6 25
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
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
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

830 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