Solved

Reading Dynamic controls like DropDownList in C#

Posted on 2007-11-21
3
6,617 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
Comment Utility
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
Comment Utility
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
Comment Utility
I understood your point. Just recreated the html on postback and it works fine

MaAny Thanks
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

743 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now