欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

用javascript为DropDownList控件下拉式选择添加一个Item至定义索引位置

程序员文章站 2024-03-04 16:23:47
用javascript为dropdownlist控件下拉式选择添加一个item至定义索引位置。 准备数据,创建一个对象,将是存储dropdownlist控件每个item数据...
用javascript为dropdownlist控件下拉式选择添加一个item至定义索引位置。
准备数据,创建一个对象,将是存储dropdownlist控件每个item数据。
复制代码 代码如下:

imports microsoft.visualbasic
namespace insus.net
public class catalog
private _id as integer
private _name as string
public property id as integer
get
return _id
end get
set(value as integer)
_id = value
end set
end property
public property name as string
get
return _name
end get
set(value as string)
_name = value
end set
end property
end class
end namespace

在.aspx放置一个dropdownlist控件
复制代码 代码如下:

<asp:dropdownlist id="dropdownlistcatalog" runat="server"></asp:dropdownlist>

在.aspx.vb绑定数据
复制代码 代码如下:

imports insus.net
partial class _default
inherits system.web.ui.page
protected sub page_load(sender as object, e as eventargs) handles me.load
if not ispostback then
data_binding()
end if
end sub
private sub data_binding()
me.dropdownlistcatalog.datasource = getdata()
me.dropdownlistcatalog.datavaluefield = "id"
me.dropdownlistcatalog.datatextfield = "name"
me.dropdownlistcatalog.databind()
end sub
private function getdata() as list(of catalog)
dim cls as new list(of catalog)
dim cl as catalog = new catalog()
cl.id = 1
cl.name = "新闻频道"
cls.add(cl)
cl = new catalog()
cl.id = 2
cl.name = "体育频道"
cls.add(cl)
cl = new catalog()
cl.id = 3
cl.name = "军事频道"
cls.add(cl)
cl = new catalog()
cl.id = 4
cl.name = "教育频道"
cls.add(cl)
return cls
end function
end class

准备数据与环境后,写javascript:
复制代码 代码如下:

window.onload = function () {
var catalog = document.getelementbyid("<%=dropdownlistcatalog.clientid%>");
var obj = document.createelement("option")
obj.text = "请选择..."
obj.value = 0
catalog.options.insertbefore(obj, catalog.options[0]);
}

demo:
用javascript为DropDownList控件下拉式选择添加一个Item至定义索引位置