我正在进行一个迷你测验,我坚持使用C#编码,检查用户从DropDownList中选择哪个ListItem。
<li><b>What is 231 mod 55?</b>
<asp:Label ID="lblQuestionResult2" runat="server" Font-Bold="true" Font-Size="16px" />
<br />
<asp:DropDownList ID="DropDownList1" runat="server" Width="55px">
<asp:ListItem>14</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
</asp:DropDownList>
</li>
我所拥有的不起作用。如何检查用户选择的内容?
if (ListItem.Equals(toString(11)))
{
lblQuestionResult2.ForeColor = System.Drawing.Color.Green;
lblQuestionResult2.Text = "Correct";
}
else
{
lblQuestionResult2.ForeColor = System.Drawing.Color.Red;
lblQuestionResult2.Text = "Incorrect";
}
答案 0 :(得分:1)
您的DropDownList
控件已经是服务器端控件。为OnSelectedIndexChanged
事件添加事件处理程序并处理它。它应该看起来像
<asp:DropDownList ID="DropDownList1"
runat="server" Width="55px" AutoPostBack="true"
OnSelectedIndexChanged="OnComboSelectionChanged">
在后面的代码中,您可以添加像这样的处理程序
protected void OnComboSelectionChanged(object sender, EventArgs e)
{
// Your code goes here.
string selectedValue = DropDownList1.SelectedValue;
}
确保使用
AutoPostBack="true"
答案 1 :(得分:0)
有两种方法可以获得它:
//One way
string selectedvalue = ddList.SelectedValue;
//Second Way
string selectedindex = ddList.SelectedItem.Text;
完整的例子:
我推出了DropDownList
和Button
<asp:DropDownList ID="ddList" runat="server">
<asp:ListItem>14</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnClick" runat="server" Text="Button" OnClick="btnClick_Click" />
我创建了一个方法,当用户点击按钮
时会触发该方法protected void btnClick_Click(object sender, EventArgs e)
{
string selectedvalue = ddList.SelectedValue;
string selectedindex = ddList.SelectedItem.Text;
}
答案 2 :(得分:0)
此MSDN页面应该有所帮助。看起来你需要做什么 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitem.selected.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
答案 3 :(得分:0)
这可能会对你有所帮助
// aspx side
<asp:DropDownList ID="DropDownList1" runat="server" Width="55px"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>14</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
</asp:DropDownList>
// cs side
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue=="11")
{
lblQuestionResult2.ForeColor = System.Drawing.Color.Green;
lblQuestionResult2.Text = "Correct";
}
else
{
lblQuestionResult2.ForeColor = System.Drawing.Color.Red;
lblQuestionResult2.Text = "Incorrect";
}
}
答案 4 :(得分:0)
<asp:DropDownList ID="DropDownList1" runat="server" Width="55px"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>14</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
</asp:DropDownList>
//背后的代码
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex!=0)
{
//your code implementation for selected value
}
}