简体   繁体   English

无法获取动态创建的控件的值C#

[英]Unable to get values of dynamically created controls c#

I have created dynamic controls on button click and I'm not able to retrieve values of dynamically created controls. 我已经在单击按钮时创建了动态控件,但无法检索动态创建的控件的值。 I am getting values of dynamic controls inside a panel. 我正在面板内获取动态控件的值。

pnlDepartment is the Panel ID. pnlDepartment是面板ID。

protected void btnValues_Click(object sender, EventArgs e)
{
    string strDDLValue = string.Empty;
    foreach (DropDownList ddl in pnlDepartment.Controls.OfType<DropDownList>())
    {
        strDDLValue = ddlName.SelectedItem.Text + "," + ddlLocation.SelectedItem.Text;
    }
}  

The strDDLValue has only first dropdown values and when it loops for the second time it still takes the first dropdown values and unable to get dynamic control values. strDDLValue仅具有第一个下拉列表值,并且在第二次循环时仍会采用第一个下拉列表值,并且无法获取动态控制值。

Please correct me if I'm making a mistake somewhere. 如果我在某个地方犯了错误,请纠正我。

Updated code: 更新的代码:

 string strDDLValue = string.Empty;
            foreach (DropDownList ddl in pnlDepartment.Controls.OfType<DropDownList>())
            {
                strDDLValue = ddl.SelectedItem.Text;
            }

You haven't used the dll variable. 您尚未使用dll变量。 If the foreach loop in the pnlDeportment only contains the name. 如果pnlDeportment中的foreach循环仅包含名称。 You will have to use this method. 您将必须使用此方法。

protected void btnValues_Click(object sender, EventArgs e)   
{
    string strDDLValue = string.Empty;
    foreach (DropDownList ddl in pnlDepartment.Controls.OfType<DropDownList>())
    {
        strDDLValue = ddl.SelectedItem.Text
    }
}  

Other wise you must create two list that adds the dropdown for the name and one for the location. 否则,您必须创建两个添加名称下拉列表的列表和一个添加位置的列表。

init your lists at the init of your page. 在页面的初始位置初始化列表。

List<DropDownList> ddlNames;
List<DropDownList> ddlLocations;

protected void btnValues_Click(object sender, EventArgs e)   
{ 
     if (dllNames.Count() == ddlLocations.Count())
     {
         for (int i = 0; i < ddlNames.Count(); i++)
         {
              strDDLValue = string.Format("{0},{1}", 
               ddlNames[i].SelectedItem.Text,
               ddlLocations[i].SelectedItem.Text );
         }
     }
}

Make sure you get the list of controls that you need by: 确保通过以下方式获得所需的控件列表:

 int i = 0;
foreach (DropDownList ddl in pnlDepartment.Controls.OfType<DropDownList>())
{
    i++;
    ddl.SelectedItem.Text = string.Format("Found:{0}",i);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM