c# - 从 ComboBox 中检索 DataSource 的内容

标签 c# asp.net

我有一个组合框,它绑定(bind)到具有三个属性的对象列表:int aint bstring x。绑定(bind)时,我将 DataTextField 设置为 x 并将 DataValueField 设置为 a。我想要做的是在集合绑定(bind)到列表后在代码隐藏中获取 b 的值。我不想使用 ViewState。我可以使用反射吗?是这样的吗?

var dataSource = ddlTest.GetDataSource();
var newDataSource = dataSource.GetType().GetProperty("_dataSource", 
    BindingFlags.NonPublic | BindingFlags.Instance);

最佳答案

我对此不确定,但您可能能够将b 作为自定义属性添加到ListItem。尝试这样的事情,看看它是否有效:

var table = new DataTable("TableName"); 

//bind the dropdown to the result set
dropDownList.DataSource = table;
dropDownList.DataBind();

//iterate through the datasource and add custom attributes for each item in the list
table.AsEnumerable().ToList().ForEach(r => 
    dropDownList.Items.FindByValue(r.Field<int>("a").ToString()).Attributes["data-field"] = r.Field<int>("b").ToString());    

如果您更喜欢使用常规的 foreach 循环:

foreach (DataRow row in table.Rows)
{
    var item = dropDownList.FindByValue(row.Field<int>("a").ToString());
    if (item != null)
    {
        item.Attributes["data-value"] = row.Field<int>("b").ToString();
    }
}

如果添加自定义属性不起作用并且您不想使用 ViewState,您可能必须将 ab 存储在值字段中,分开由定界符。这可能会很痛苦,因为您必须解析项目以获取值,但考虑到您的要求,如果自定义属性不起作用,这可能是最佳选择。

关于c# - 从 ComboBox 中检索 DataSource 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10105206/

相关文章:

asp.net - 覆盖 Elmah 记录的错误消息

c# - ASP.NET 跨子域单点登录 Cookie

c# - 两个不同的 Controller 可以访问 mvc 中的单个 View 吗?

c# - C# 中的异步套接字

c# - INotifyPropertyChanged 更新 ontextchange

c# - 如何使用 Telegram API 从 Telegram channel 获取消息

c# - C# 中的简单 SQL 选择?

c# - c#捕获鼠标点击事件

c# - 我该如何排序这个列表?

asp.net - 网页抓取一个棘手的 asp.net 页面