You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ASP.NET绑定数据源的ListBox选中项Name值存入字符串变量

在ASP.NET中获取ListBox选中项的name值

前提设置

绑定ListBox时,除了已设置的DataValueField="id",需补充设置DataTextField="name",确保每一项的文本对应数据源的name列:

// 假设yourDataSource是查询返回的DataTable/实体集合等
l1.DataSource = yourDataSource;
l1.DataTextField = "name";
l1.DataValueField = "id";
l1.DataBind();

服务器端获取(PostBack场景)

单选模式(SelectionMode="Single")

直接通过SelectedItem.Text获取选中项的name值:

string selectedName = string.Empty;
if (l1.SelectedItem != null)
{
    selectedName = l1.SelectedItem.Text;
}

多选模式(SelectionMode="Multiple")

遍历所有选项,收集选中项的name值:

List<string> selectedNames = new List<string>();
foreach (ListItem item in l1.Items)
{
    if (item.Selected)
    {
        selectedNames.Add(item.Text);
    }
}
// 可选:合并为逗号分隔的字符串
string combinedNames = string.Join(", ", selectedNames);

客户端获取(JavaScript,无需PostBack)

单选模式

通过DOM遍历选项,获取选中项的text属性:

var listBox = document.getElementById('<%= l1.ClientID %>');
var selectedName = '';
for (var i = 0; i < listBox.options.length; i++) {
    if (listBox.options[i].selected) {
        selectedName = listBox.options[i].text;
        break;
    }
}

多选模式

收集所有选中项的text属性,可合并为字符串:

var listBox = document.getElementById('<%= l1.ClientID %>');
var selectedNames = [];
for (var i = 0; i < listBox.options.length; i++) {
    if (listBox.options[i].selected) {
        selectedNames.push(listBox.options[i].text);
    }
}
var combinedNames = selectedNames.join(', ');

内容的提问来源于stack exchange,提问作者Arindam Singha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 18:31:09