2

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?

2 Answers 2

5

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();
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks.So I should return a Dictionary<> instead of a string[] from my GetGlobalUserList() method? And then how to bind that to the .Value and .Text?
That works, I just need to swap Key with Value to have the strings displayed instead of the ints. Thanks again
@sd_dracula: Just keep one thing in mind that Keys are unique while Values can be repetitive in Dictionary.
Should be fine since the Keys I supply are unique (primary keys) from a table anyway.
2

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();

2 Comments

.DisplayMember is not valid for asp:listbox it seems
@sd_dracula Yes, it should be change to DataTextField

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.