我需要一个美国各州的下拉列表。我可能需要在各个页面上显示此下拉列表。我不想总是为每个州创建一个listitem,而是想要一个简单的控件。我不想要UserControl - 我想扩展现有的dropdownlist控件。我知道我之前在前雇主那里做过这件事,但对于我的生活,我不记得怎么做了!
我不能为每个州做这样的事情吗?如果是这样,在哪里?
MyBase.Items.Add(New ListItem("Illinois","IL"))
有任何想法吗?
由于
答案 0 :(得分:2)
您所要做的就是创建一个新类并从适当的控件继承:
/// <summary>
/// </summary>
[DefaultProperty("DataTable"),
ToolboxData("<{0}:ExtendedDropDownlist runat=server></{0}:ExtendedDropDownlist>")]
public class ExtendedDropDownList : DropDownList
/// <summary>
/// Render this control to the output
/// parameter specified.
/// </summary>
/// <param name="output"> The HTML writer to
/// write out to </param>
protected override void Render(HtmlTextWriter output)
{
//output.Write(Text);
base.Render(output);
}
在构造函数中,只需添加相应的列表框项即可。
您可能需要将其放在不同的项目中并引用该DLL。我想我记得那件事,但是我已经有一段时间了,因为我不得不这样做。
答案 1 :(得分:0)
扩展DropDownList控件并覆盖OnLoad事件,并添加如下项目:
protected override void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.Items.Add(new ListItem("Illinois","IL"));
}
}
答案 2 :(得分:0)
<ToolboxData("<{0}:StateDropDownList runat=server></{0}:StateDropDownList>")> _
Public Class StateDropDownList
Inherits DropDownList
Protected Overrides Sub RenderContents(ByVal output As HtmlTextWriter)
output.Write(Text)
End Sub
Protected Overrides Sub RenderChildren(ByVal writer As System.Web.UI.HtmlTextWriter)
MyBase.RenderChildren(writer)
End Sub
Private Sub LoadStates()
MyBase.Items.Add(New ListItem("Alabama", "AL"))
'Additional states removed for size
MyBase.Items.Add(New ListItem("Wyoming", "WY"))
End Sub
Public Sub New()
'tried does not work
' LoadStates()
End Sub
Private Sub StateDropDownList_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
'tried does not work
' LoadStates()
End Sub
Private Sub StateDropDownList_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'tried does not work
'If Not Page.IsPostBack Then
' LoadStates()
'End If
End Sub
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
MyBase.Render(writer)
End Sub
End Class
答案 3 :(得分:0)
public class DropDownListStates : System.Web.UI.WebControls.DropDownList
{
protected override void CreateChildControls()
{
if (Items.Count > 0) return;
Items.Add(new System.Web.UI.WebControls.ListItem("AL"));
// other states here...
Items.Add(new System.Web.UI.WebControls.ListItem("WY"));
}
}