扩展RadiobuttonList控件以在.NET中包含“其他”选项

时间:2016-02-16 18:30:18

标签: c# .net custom-controls radiobuttonlist

我正在尝试扩展.NET RadioButtonList控件以自动包含“其他”的文本框。但是,我似乎无法检索文本框的值。我试过使用和.NET Textbox以及HtmlInputText控件一样无济于事。在我尝试检索它之前,这个值似乎已经丢失了。

任何想法我做错了什么?

public class RadioButtonListExtended : RadioButtonList
{        
    public bool AddOther
    {
        get
        {
            object o = ViewState["AddOther"];
            if (o == null)
                return false;
            return bool.Parse(o.ToString());
        }
        set
        {
            ViewState["AddOther"] = value.ToString();
        }
    }

    public string OtherTextValue
    {
        get
        {
            EnsureChildControls();
            return txtOther.Value;
        }
        set
        {
            EnsureChildControls();
            txtOther.Value = value.ToString();
        }
    }

    private HtmlInputText txtOther;

    protected override void CreateChildControls()
    {
        txtOther = new HtmlInputText();
        txtOther.ID = "txtOther";
        Controls.Add(txtOther);
    }

    protected override void Render(HtmlTextWriter writer)
    {
        EnsureChildControls();

        writer.WriteLine("<table class='radios'>");
        writer.WriteLine("<tr>");

        // Write all the radio buttons
        for (int i = 0; i < this.Items.Count; i++)
        {
            if (AddOther && (i == this.Items.Count - 1))
                writer.WriteLine("<td class='fs_otherSelect'>");
            else
                writer.WriteLine("<td>");

            writer.WriteLine("<input "
                + "id='" + this.ClientID + "_" + i + "'"
                + " type='radio' "
                + "name='" + this.ClientID.Replace("_", "$") + "' "
                + "value='" + this.Items[i].Value + "' "
                + ((SelectedValue == this.Items[i].Value) ? "checked" : "")
                + ">");

            writer.WriteLine("<label " + "for='" + this.ClientID + "_" + i + "'>" + this.Items[i].Text + "</label>");

            writer.WriteLine("</td>");

        }

        if (AddOther)
        {
            writer.WriteLine("<tr class='fs_otherEntry'>");
            writer.WriteLine("<td colspan='" + ((Columns > 0) ? Columns : this.Items.Count) + "'>");
            txtOther.RenderControl(writer);
            writer.WriteLine("</td>");
            writer.WriteLine("</tr>");
        }

        writer.WriteLine("</tr>");
        writer.WriteLine("</table>");
        writer.WriteLine("</div>");
    }

0 个答案:

没有答案