ASP.NET: Listbox datasource and databind

后端 未结 3 476
天涯浪人
天涯浪人 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 objects;
      public void OnLoad(object sender, EventArgs e) {
        objects = new List();
        //add objects
        lstbx.DataSource = objects;
        lstbx.DataTextField = "text";
        lstbx.DataValueField = "value";
        lstbx.DataBind();
      }
    }
    

提交回复
热议问题