【问题标题】:How to get components of a panel in asp.net?如何在 asp.net 中获取面板的组件?
【发布时间】:2024-01-06 06:24:01
【问题描述】:

我有一个面板,其中包含一些 asp.net 组件。我正在根据我的数据生成这些组件(如下拉列表、复选框、文本框等)。

下拉示例:

System.Web.UI.WebControls.Panel comboBoxOlustur(ANKETQUESTIONBec bec)
{
    System.Web.UI.WebControls.Panel p = new System.Web.UI.WebControls.Panel();

    Table tb = new Table();
    TableRow tr = new TableRow();
    TableCell tdSoru = new TableCell(), tdComboBox = new TableCell();
    System.Web.UI.WebControls.DropDownList cmb = new System.Web.UI.WebControls.DropDownList();

    tdSoru.Text = bec.QUESTION;
    tdSoru.Width = 350;
    tdSoru.VerticalAlign = VerticalAlign.Top;

    if (bec.WIDTH != null)
        cmb.Width = (short)bec.WIDTH;
    else
        cmb.Width = 200;
    cmb.Height = 18;
    //data operations
    QUESTIONSELECTIONDEFINITIONBlc blc = new QUESTIONSELECTIONDEFINITIONBlc();
    List<QUESTIONSELECTIONDEFINITIONBec> secenekler = blc.GetByAnketQueID(bec.ID,1);

    if (secenekler != null)
    {
        ListItem li;
        li = new ListItem();
        li.Value = "-1";
        li.Text = "--Seçiniz--";
        cmb.Items.Add(li);
        for (int i = 0; i < secenekler.Count; i++)
        {
            li = new ListItem();
            li.Value = secenekler[i].ID.ToString();
            li.Text = secenekler[i].NAME;

            cmb.Items.Add(li);
        }
    }
    //end of data operations
    tdComboBox.Controls.Add(cmb);
    tr.Cells.Add(tdSoru);
    tr.Cells.Add(tdComboBox);
    tb.Rows.Add(tr);
    p.Controls.Add(tb);

    return p;
}

在这一点上,我想访问这个下拉列表以获取它的价值。我该如何实现呢?

【问题讨论】:

  • 我现在正在做的事情——根据数据库结果加载控件——他们通过在 textchanged 上使用 javascript 将值保存到命名的隐藏字段中来做到这一点......他们将值放入JSON 格式,它使用 JavaScriptSerializer 在后面的代码中读取它们。对不对,我不知道。
  • 明白,但我有保存数据的服务。我需要使用它。所以我需要所有组件的数据。

标签: c# asp.net panel


【解决方案1】:

我怀疑最好的方法是适当地命名您的控件,然后使用FindControl

您可能需要使用FindControl recursively 以便轻松搜索多个图层。

根据您的需要,声明一个变量或变量数组来跟踪添加的每个控件也可能有意义。这种方法有可能用于消除搜索控件的需要,因此效率更高。

【讨论】:

  • 组件的数量是动态的。可以有 1 或 10 个下拉菜单、文本和复选框。我需要所有这些组件而不是特定的组件。所以我认为在这种情况下我不能使用 FindControl。我错了吗?
  • 正如我刚才所说,您可以使用FindControl()。但正如我刚才所说,您可以简单地存储对变量的引用。 List&lt;Control&gt; 可以很容易地用于存储任意数量的变量引用。
【解决方案2】:

我已经使用这样的东西来获取所有子控件:

    private void GetAllControls(Control container, Type type)
    {
        foreach (Control control in container.Controls)
        {
            if (control.Controls.Count > 0)
            {
                GetAllControls(control, type);
            }

            if (control.GetType() == type) ControlList.Add(control);
        }
    }

然后执行以下操作:

    this.GetAllControls(this.YourPanel, typeof(Button));
    this.GetAllControls(this.YourPanel, typeof(DropDownList));
    this.GetAllControls(this.YourPanel, typeof(TextBox));
    this.GetAllControls(this.YourPanel, typeof(CheckBox));

【讨论】:

    最近更新 更多