Solved

Reading Dynamic controls like DropDownList in C#

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial

738 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