Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET: Listbox datasource and databind

I have an empty listbox on .aspx page

lstbx_confiredLevel1List

I am generating two lists programatically

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

I want to load lstbx_confiredLevel1List list box on .aspx page with above values and text. So i am doing following:

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

but it does not load the lstbx_confiredLevel1List with l1ListText and l1ListValue.

Any ideas?

like image 561
user1889838 Avatar asked Dec 15 '22 16:12

user1889838


2 Answers

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;
like image 103
Tim Schmelter Avatar answered Dec 28 '22 00:12

Tim Schmelter


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();
like image 30
GeorgesD Avatar answered Dec 28 '22 01:12

GeorgesD