c# - 获取动态添加的子控件以显示在 UI 中

标签 c# asp.net webforms

我正在尝试创建一个扩展 RadoButtonList 的 RadioButtonListWithOther 类,但我无法在页面上呈现“其他”文本框。当我在调试时单步执行时,我可以在父控件的控件集合中看到该控件,但它仍然没有呈现。知道我在这里做错了什么吗?

public class RadioButtonListWithOther : RadioButtonList
{
    private TextBox _otherReason;

    public RadioButtonListWithOther()
    {
        _otherReason = new TextBox();
        _otherReason.TextMode = TextBoxMode.MultiLine;
        _otherReason.Rows = 6;
        _otherReason.Width = Unit.Pixel(300);
        _otherReason.Visible = true;
    }

    protected override void CreateChildControls()
    {
        this.Controls.Add(_otherReason);
        this.EnsureChildControls();
        base.CreateChildControls();
    }

    protected override void OnSelectedIndexChanged(EventArgs e)
    {
        _otherReason.Enabled = false;

        if (OtherSelected())
        {
            _otherReason.Enabled = true;
        }

        base.OnSelectedIndexChanged(e);
    }

    public override string Text
    {
        get
        {
            if (OtherSelected())
            {
                return _otherReason.Text;
            }
            return base.Text;
        }
        set
        {
            base.Text = value;
        }
    }
    public override bool Visible
    {
        get
        {
            return base.Visible;
        }
        set
        {
            //Push visibility  changes down to the children controls
            foreach (Control control in this.Controls)
            {
                control.Visible = value;
            }
            base.Visible = value;
        }
    }

    private bool OtherSelected()
    {
        if (this.SelectedItem.Text == "Other")
        {
            return true;
        }
        return false;
    }
}

这是我将此控件的实例添加到 WebForm 的代码:

protected override void CreateChildControls()
{
    var whyMentorOptions = new Dictionary<string, string>();
    whyMentorOptions.Add("Option 1", "1");
    whyMentorOptions.Add("Option 2", "2");
    whyMentorOptions.Add("Option 3", "3");
    whyMentorOptions.Add("Other", "Other");

    mentorWhy = new RadioButtonListWithOther
    {
        DataSource = whyMentorOptions
    };
    this.mentorWhy.DataTextField = "Key";
    this.mentorWhy.DataValueField = "Value";
    this.mentorWhy.DataBind();

    Form.Controls.Add(mentorWhy);

    base.CreateChildControls();
}

最佳答案

RadioButtonList类在呈现时完全忽略其子控件(它只对其 Items 集合的内容感兴趣)。

您必须自己渲染文本框:

protected override void Render(HtmlTextWriter writer)
{
    base.Render(writer);
    _otherReason.RenderControl(writer);
}

关于c# - 获取动态添加的子控件以显示在 UI 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4487371/

相关文章:

c# - 在方法参数上设置名称

c# - 获取项目中引用的所有程序集中的所有接口(interface)类型

c# - 通过LDAP登录认证

c# - 当搜索没有结果时抛出一个弹出窗口

c# - C# 日志记录的性能技巧

javascript - 删除不起作用(保存后无法删除数据)

c# - Paypal 立即购买按钮快速结帐

asp.net - RouteTable.Routes 和 HttpConfiguration.Routes 的区别?

asp.net - 无法理解从 HTML 导出 Excel 电子表格的代码

c# - 获取页面上特定类型的所有 Web 控件