Listbox in asp.net not getting selected items(asp.net中的列表框没有得到选定的项目)
问题描述
我有多个下拉菜单和我网页中的列表框.
I have multiple dropdown & listbox in my webpage.
我正在尝试从 lstCatID 列表框中获取 CategoryID 列表,我可以使用类别名称填充列表框.
I am trying to get a list of CategoryID from a lstCatID listbox i am able to populate the listbox with category name.
如果我在第一次尝试时没记错,我的代码运行良好,之后我做了一些更改,然后它声明总是选择第一个项目 x 时间
If i remember correctly in first attempt my code worked fine, after that i made some change then it stated to always get the first item selected x No. of time
<asp:ListBox ID="lstCatID" runat="server" DataTextField="CategoryName"
DataValueField="CategoryID" SelectionMode="Multiple" CssClass="lstListBox">
</asp:ListBox>
protected void Button1_Click(object sender, EventArgs e)
{
string CatID = string.Empty;
foreach (ListItem li in lstCatID.Items)
{
if (li.Selected == true)
{
// Response.Write();
CatID += lstCatID.SelectedItem.Value + ",";
}
}
Response.Write(CatID);
}
我不确定出了什么问题,我检查了 MSDN,它显示的方法完全相同.
I am not sure what is going wrong i checkd MSDN it show exactly the same way of doing it.
可能是我做错了什么.
只需使用 Firefox 添加,我就能看到多个选定的值具有选定的属性.
Just to add using firefox i am able to see multiple selected value have selected property.
<option value="3" selected="selected">One</option>
<option value="2">Two</option>
<option value="29" selected="selected">Three</option>
<option value="25" selected="selected">Four</option>
<option value="22" >Five</option>
在这种情况下,我的输出将是 3,3,3
My output in this case will be 3,3,3
我会很感激这方面的帮助
I would appreciate help in this regard
推荐答案
您每次都将其设置为相同的值:
You are setting it to the same value every time:
foreach (ListItem li in lstCatID.Items)
{
if (li.Selected == true)
{
// you are always using lstCatID.SelectedItem.Value.
CatID += lstCatID.SelectedItem.Value + ",";
}
}
当你真正想要你的循环中被选中的项目的值时:
When you actually want the value of the item in your loop that is selected:
foreach (ListItem li in lstCatID.Items)
{
if (li.Selected == true)
{
// get the value of the item in your loop
CatID += li.Value + ",";
}
}
这篇关于asp.net中的列表框没有得到选定的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:asp.net中的列表框没有得到选定的项目
基础教程推荐
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
