我正在尝试创建一个扩展 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/