3

I'm fairly new to asp.net and especially LINQ and SQL.

Say I have a table "Employees" with fields "Lastname", "Firstname", and "ID".

I want to bind this to a list box. I want the list box to display it's contents like "$LASTNAME, $FIRSTNAME" and I want the value of each item to be "ID".

It's trivial to bind either name column to the listbox and the values accordingly, but I can't figure out how to do this..

Thanks in advance

2 Answers 2

7

You could try something like this:

var datasource = from employee in employees 
                 select new
                 { 
                     Name = employee.lastName + ", " + employee.firstName, 
                     Id = employee.ID 
                 };

myListBox.DataSource = datasource;
myListBox.DataTextField = "Name";
myListBox.DataValueField = "Id";
myListBox.DataBind();

This constructs a list of anonymous types from your employee table to bind your listbox to.

Sign up to request clarification or add additional context in comments.

1 Comment

Looking at examples I knew it was something like this. The new {} syntax was unfamiliar to me. Thank you!
1

Unfortunately I'm not terribly familiar with LINQ, but if you just want to display the names like that you could do this in a SQL query:

SELECT LASTNAME + ', ' + FIRSTNAME AS FULLNAME, ID FROM TableName

And then set the value of the DataTextField to FULLNAME and the DataValueField to ID.

Comments

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.