sd_dracula
sd_dracula

Reputation: 3896

asp.net listBox text/value

Basically I need to populate a listBox's .Text value with a string and its .Value value with an int. By doing this:

lbUsers.DataSource = new UserManagerBO().GetGlobalUserList();
lbUsers.DataBind();

This assigns a string to both .Value and .Text.

Now I know GetGlobalUserList() returns a string[] which is why I'm getting the behaviour above, so how to go about returning the int values along with the string ones? Maybe go 2D array? And then how to bind those results to the listbox?

Upvotes: 2

Views: 7794

Answers (2)

Damith
Damith

Reputation: 63065

Create custom class with user properties. this can be re used when you deal with Global Users

public class CustomClass()
{
    public int ID { get; set; }
    public int Name  { get; set; }
}

return collection of CustomClass objects from GetGlobalUserList(), you need to change the signature and logic of GetGlobalUserList method. Ones you done that,

lbUsers.DataSource = new UserManagerBO().GetGlobalUserList();

set DataTextField and DataValueField of your listbox

lbUsers.DataTextField  = "Name";
lbUsers.DataValueField = "ID";
lbUsers.DataBind();

Upvotes: 2

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48558

Option 1 Let that method return string[] and for value pick SelectedIndex.

Option 2 Create a custom class as Damith answers.

Option 3 A Dictionary<int, string> will suffice.

Dictionary Keys for ListBox Value and Dictionary Values for ListBox Text.

Say this is the dictionary returned by your method

//Adding key value pair to the dictionary
Dictionary<int, string> dStudent = new Dictionary<int, string>();
dStudent.Add(0, "Eena");
dStudent.Add(1, "Meena");
dStudent.Add(2, "Deeka");
dStudent.Add(3, "Tom");
dStudent.Add(4, "Dick");
dStudent.Add(5, "Harry");
dStudent.Add(6, "Yamla");
dStudent.Add(7, "Pagla");
dStudent.Add(8, "Dewana");
dStudent.Add(9, "Guru");
dStudent.Add(10, "Sholay");

Step 2:

Now it's time to bind a Dictionary pair with your listbox. The following code binds to listbox.

//binding to the list
lst.DataTextField = "Value";
lst.DataValueField = "Key";
lst.DataSource = dStudent;
lst.DataBind();

Upvotes: 5

Related Questions