ASP.NET: Listbox datasource and databind

纵饮孤独 提交于 2019-11-29 11:29:40

Why don't you use the same collection as DataSource? It just needs to have two properties for the key and the value. You could f.e. use a Dictionary<string, string>:

var entries = new Dictionary<string, string>();
// fill it here
lstbx_confiredLevel1List.DataSource = entries;
lstbx_confiredLevel1List.DataTextField = "Value";
lstbx_confiredLevel1List.DataValueField = "Key";
lstbx_confiredLevel1List.DataBind();

You can also use an anonymous type or a custom class.

Assuming that you have already these lists and you need to use them as DataSource. You could create a Dictionary on the fly:

Dictionary<string, string> dataSource = l1ListText
           .Zip(l1ListValue, (lText, lValue) => new { lText, lValue })
           .ToDictionary(x => x.lValue, x => x.lText);
lstbx_confiredLevel1List.DataSource = dataSource;

You'd better used a dictionnary:

Dictionary<string, string> list = new Dictionary<string, string>();
...
lstbx_confiredLevel1List.DataSource = list;
lstbx_confiredLevel1List.DataTextField = "Value";
lstbx_confiredLevel1List.DataValueField = "Key";
lstbx_confiredLevel1List.DataBind();

Unfortunately the DataTextField and DataValueField are not used like that. They are the text representation of the fields they're supposed to show of the current item that's being databound in the DataSource.

If you had an object that held both text and value, you'd make a list of it and set that to datasource like this:

public class MyObject {
  public string text;
  public string value;

  public MyObject(string text, string value) {
    this.text = text;
    this.value = value;
  }
}

public class MyClass {
  List<MyObject> objects;
  public void OnLoad(object sender, EventArgs e) {
    objects = new List<MyObjcet>();
    //add objects
    lstbx.DataSource = objects;
    lstbx.DataTextField = "text";
    lstbx.DataValueField = "value";
    lstbx.DataBind();
  }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!