ASP.NET: Listbox datasource and databind

后端 未结 3 477
天涯浪人
天涯浪人 2020-12-19 21:58

I have an empty listbox on .aspx page

lstbx_confiredLevel1List

I am generating two lists programatically

List         


        
相关标签:
3条回答
  • 2020-12-19 22:37

    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();
      }
    }
    
    0 讨论(0)
  • 2020-12-19 22:47

    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();
    
    0 讨论(0)
  • 2020-12-19 22:57

    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;
    
    0 讨论(0)
提交回复
热议问题