Solved

Reading Dynamic controls like DropDownList in C#

Posted on 2007-11-21
3
6,631 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

863 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

23 Experts available now in Live!

Get 1:1 Help Now