Subclassing DropDownList in ASP.NET

后端 未结 2 393
时光取名叫无心
时光取名叫无心 2020-12-18 07:41

I want to subclass the built-in DropDownList in ASP.NET so that I can add functionality to it and use it in my pages. I tried doing this with a UserControl but found that it

2条回答
  •  自闭症患者
    2020-12-18 08:32

    In a comment, you clarify your goal: "The only thing I want to do with it is add an InitialValue property that defines the first value that is always present in the DDL."

    I don't think you need to create a special user control or custom control to accomplish that.

    I often use this code throughout my web apps to populate list controls. You pass in a boolean indicating whether an additional ListItem is to be added at the top of the list, and the text for that item.

        public static void BindListControl (ListControl ctl, SqlDataReader dr,
            String textColumn, String valueColumn, bool addBlankRow, string blankRowText)
        {
            ctl.Items.Clear();
            ctl.DataSource = dr;
            ctl.DataTextField = textColumn;
            ctl.DataValueField = valueColumn;
            ctl.DataBind();
    
            if (addBlankRow == true) ctl.Items.Insert(0, blankRowText);
        }
    

    This is useful, for example, if you want every DropDownList to have as its initial value a blank, or text such as "Select a city".

提交回复
热议问题