Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Reading Dynamic controls like DropDownList in C#

Posted on 2007-11-21
3
Medium Priority
?
6,681 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
[X]
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
  • 2
3 Comments
 
LVL 33

Accepted Solution

by:
raterus earned 2000 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

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

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

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

721 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