我有以下代码来显示下拉列表,但在下拉列表中显示时,看起来名称和值对都是相同的。
aspx.cs:
DropDownList dp = new DropDownList();
dp.ID = ToString();
dp.Items.Add(new ListItem("test1", "This is test1"));
dp.Items.Add(new ListItem("test2", "This is test2"));
Script.DataSource = dp.Items;
Script.DataBind();
ASPX:
<asp:DropDownList ID="Script" runat="server" OnSelectedIndexChanged="ScriptSelected" AutoPostBack="true">
</asp:DropDownList>
当我调试时,知道名称和值都相同,如下所示
<select name="Script" onchange="javascript:setTimeout('__doPostBack(\'Script\',\'\')', 0)" id="Script">
<option value="test1">test1</option>
<option value="test2">test2</option>
</select>
但需要如下
<select name="Script" onchange="javascript:setTimeout('__doPostBack(\'Script\',\'\')', 0)" id="Script">
<option value="test1">This is test1</option>
<option value="test2">This is test2</option>
</select>
答案 0 :(得分:3)
您需要为控件指定DataValueField和DataTextField。
<asp:DropDownList ID="Script" runat="server" OnSelectedIndexChanged="ScriptSelected" AutoPostBack="true" DataValueField="Value" DataTextField="Text">
</asp:DropDownList>
或者,如果您想在服务器端执行此操作,
DropDownList dp = new DropDownList();
dp.ID = ToString();
dp.DataTextField = "Text";
dp.DataValueField = "Value";
dp.Items.Add(new ListItem("test1", "This is test1"));
dp.Items.Add(new ListItem("test2", "This is test2"));
Script.DataSource = dp.Items;
Script.DataBind();