【问题标题】:Unable to get values of dynamically created controls c#无法获取动态创建的控件的值 c#
【发布时间】:2018-06-17 04:09:29
【问题描述】:

我在按钮单击时创建了动态控件,但我无法检索动态创建的控件的值。我在面板中获取动态控件的值。

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;
    }
}  

strDDLValue 只有第一个下拉值,当它第二次循环时,它仍然采用第一个下拉值,无法获取动态控制值。

如果我在某处犯了错误,请纠正我。

更新代码:

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

【问题讨论】:

  • 如何将动态控件添加到pnlDepartment
  • 您没有使用在您的foreach 中声明的ddl 变量。
  • 这是因为您使用的是静态对象(ddlNameddlLocation),而不是 foreach 循环中的 ddl DropDownList。
  • 您需要使用 FindChild 方法。看看这个Question

标签: c# asp.net .net c#-4.0 dynamic-controls


【解决方案1】:

您还没有使用 dll 变量。如果 pnlDeportment 中的 foreach 循环只包含名称。您将不得不使用此方法。

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

否则,您必须创建两个列表,分别添加名称下拉列表和位置下拉列表。

在您的页面初始化时初始化您的列表。

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 );
         }
     }
}

确保您通过以下方式获得所需的控件列表:

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

【讨论】:

  • 我正在面板内创建两个动态下拉控件,但无法获取动态创建的控件值的值。用代码更新帖子。
  • 我已经更新了我的分析器,请确保你得到你想要的列表。
猜你喜欢
  • 1970-01-01
  • 2020-06-18
  • 1970-01-01
  • 2013-04-24
  • 2013-04-26
  • 1970-01-01
  • 2010-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多