我有一个下拉列表,我绑定了一个List,如:
var ddlLst2 = new List<string> { "Audi", "BMW", "Ford", "Vauxhall"};
ddlLst2.Sort();
foreach (var item in ddlLst2)
{
DropDownList2.Items.Add(new ListItem(item));
}
结果:
<select id="DropDownList2" onchange="javascript:setTimeout('__doPostBack(\'DropDownList2\',\'\')', 0)" name="DropDownList2">
<option value="--Please Select--" selected="selected"></option>
<option value="Audi"></option>
<option value="BMW"></option>
<option value="Ford"></option>
<option value="Vauxhall"></option>
</select>
但我想在每个项目中添加一个属性,预期结果如下:
预期结果:
<select id="DropDownList2" onchange="javascript:setTimeout('__doPostBack(\'DropDownList2\',\'\')', 0)" name="DropDownList2">
<option value="--Please Select--" selected="selected"></option>
<option value="Audi" code="1"></option>
<option value="BMW" code="2"></option>
<option value="Ford" code="3"></option>
<option value="Vauxhall" code="4"></option>
</select>
正如您在上面看到的,添加了一个额外的属性"code"
,code
的值来自查询。
答案 0 :(得分:1)
foreach (var item in ddlLst2)
{
ListItem tmp = new ListItem();
tmp.Text = item.ToString();
tmp.Attributes.Add("AttribName", "AttribValue");
DropDownList2.Items.Add(tmp);
}
或类似的东西......玩弄tmp的可用属性......
答案 1 :(得分:1)
void Main()
{
var ddlLst2 = new List<string> { "Audi", "BMW", "Ford", "Vauxhall"};
ddlLst2.Sort();
var ctrls = new List<ListItem>();
int i =0;
foreach (var item in ddlLst2)
{
//DropDownList2.Items.Add(new ListItem(item));
ListItem li = new ListItem(item);
li.Attributes.Add("code", i.ToString());
ctrls.Add(li);
i++;
}
foreach (ListItem element in ctrls)
{
Console.WriteLine(element.Attributes["code"]);
}
}
答案 2 :(得分:0)
对于JS事件:您可以从您的javascript订阅它。即使用JQuery:
$('#DropDownList2').change(function() { alert("Fired!"); });
答案 3 :(得分:0)
protected void dropdownlist_DataBound(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataView dv = (DataView)sqldatasource.Select(DataSourceSelectArguments.Empty);
dt = dv.ToTable();
foreach (DataRow dr in dt.Rows)
{
dropdownlist.Items.FindByValue(dr[0].ToString()).Attributes.Add("attr0", dr[2].ToString());
dropdownlist.Items.FindByValue(dr[0].ToString()).Attributes.Add("attr1", dr[3].ToString());
dropdownlist.Items.FindByValue(dr[0].ToString()).Attributes.Add("attr2", dr[4].ToString());
}
}