C# 如何检查是否选择了ListItem?
我正在做一个小测验,我被卡在C#编码上,检查用户从下拉列表中选择了哪个列表项C# 如何检查是否选择了ListItem?,c#,asp.net,C#,Asp.net,我正在做一个小测验,我被卡在C#编码上,检查用户从下拉列表中选择了哪个列表项 <li><b>What is 231 mod 55?</b> <asp:Label ID="lblQuestionResult2" runat="server" Font-Bold="true" Font-Size="16px" /> <br />
<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>
有两种方法可以获得它:
//One way
string selectedvalue = ddList.SelectedValue;
//Second Way
string selectedindex = ddList.SelectedItem.Text;
完整示例:
我已经放置了一个下拉列表
和一个按钮
<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" />
此MSDN页面应该会有所帮助。看来你需要做些什么 这可能会对您有所帮助 //aspx侧
<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>
您的
DropDownList
控件已经是服务器端控件。为OnSelectedIndexChanged
事件添加事件处理程序并对其进行处理。应该是这样的
<asp:DropDownList ID="DropDownList1"
runat="server" Width="55px" AutoPostBack="true"
OnSelectedIndexChanged="OnComboSelectionChanged">
确保你使用
AutoPostBack="true"
检查这一个。'DropDownList1.SelectedValue'返回一个字符串,因此我们可能能够摆脱多余的'.ToString()'方法调用。只是好奇,为什么我需要AutoPostBack=“true”@那么如何将这些值获取到服务器?您需要将这些值发送到服务器进行筛选。或者,您可以将jquery与ajax调用一起使用。@trama“AutoPostback”表示当用户更改选择时是否会自动回发到服务器。@Ravi我不确定我是否理解您的问题。如果您引用的是下拉框中的所有项,则可以从“items”属性(这是一个集合)获取它。
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";
}
}
<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"
<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
}
}