4

.aspxページに空のリストボックスがあります

lstbx_confiredLevel1List

プログラムで2つのリストを生成しています

List<String> l1ListText = new List<string>(); //holds the text 
List<String> l1ListValue = new List<string>();//holds the value linked to the text

lstbx_confiredLevel1List上記の値とテキストを含むリストボックスを.aspxページにロードしたい。だから私は次のことをしています:

lstbx_confiredLevel1List.DataSource = l1ListText;
lstbx_confiredLevel1List.DataTextField = l1ListText.ToString();
lstbx_confiredLevel1List.DataValueField = l1ListValue.ToString();
lstbx_confiredLevel1List.DataBind();

lstbx_confiredLevel1Listただし、 withl1ListTextとはロードされませんl1ListValue

何か案は?

4

3 に答える 3

11

と同じコレクションを使用しないのはなぜDataSourceですか? キーと値の 2 つのプロパティが必要なだけです。を使用できます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();

匿名型またはカスタム クラスを使用することもできます。

これらのリストが既にあり、それらを DataSource として使用する必要があると仮定します。その場で作成できますDictionary

Dictionary<string, string> dataSource = l1ListText
           .Zip(l1ListValue, (lText, lValue) => new { lText, lValue })
           .ToDictionary(x => x.lValue, x => x.lText);
lstbx_confiredLevel1List.DataSource = dataSource;
于 2012-12-14T13:12:05.857 に答える
1

辞書を使用した方がよいでしょう:

Dictionary<string, string> list = new Dictionary<string, string>();
...
lstbx_confiredLevel1List.DataSource = list;
lstbx_confiredLevel1List.DataTextField = "Value";
lstbx_confiredLevel1List.DataValueField = "Key";
lstbx_confiredLevel1List.DataBind();
于 2012-12-14T13:11:20.457 に答える
0

残念ながら、DataTextFieldDataValueFieldはそのようには使用されません。これらは、DataSource でデータバインドされている現在のアイテムを表示することになっているフィールドのテキスト表現です。

テキストと値の両方を保持するオブジェクトがある場合は、そのリストを作成し、次のように datasource に設定します。

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();
  }
}
于 2012-12-14T13:17:36.487 に答える