views:

122

answers:

3

I'm using LinqToSql like this with a CheckBoxList in ASP.NET:

var teachers = from x in dc.teachers select x;  
cbl.DataSource = teachers;  
cbl.DataTextField = "name";  
cbl.DataValueField = "teacherID";  
cbl.DataBind();  

I want to display both "firstname" and "name" in the DataTextField however. I found this solution but I'm using LINQ: http://stackoverflow.com/questions/839223/concatenate-two-fields-in-a-dropdown

How do I do this?

+1  A: 
var teachers = from x in dc.teachers 
    select new {
        name = x.firstname + " " + x.name, 
        x.teacherID};

cbl.DataSource = teachers;
cbl.DataTextField = "name";
cbl.DataValueField = "teacherID";
cbl.DataBind();
Dave Markle
+2  A: 

I would extend your teacher's LINQ class, add a custom readonly property called fullName and set it equal to firstName + ' ' + name. Then, set your cbl.DataTextField = fullName

Example in VB.NET

Partial Public Class Teacher

    Public ReadOnly Property FullName() As String
        Get
            Return Me.FirstName & " " & Me.Name
        End Get
    End Property

End Class

This is reusable anywhere else that you may need to use a full name attribute.

Tommy
Thanks a lot.Doing this at DB level seems even better. (Because it would work regardless of using LINQ).Any advice on such an approach together with LINQ?
kversch
Hey kversch, sorry, but I am not exactly sure what you mean by 'at the DB level'. In reality, I can see three ways to accomplish what you are trying to do. 1) In the database tables, have a full name column that you populate with the first and last names. I wouldn't recommend this as you are storing extraneous data. 2) In your own SQL queries, you can do Select Fname + ' ' + LName as fullname From... This will work, but if you are using LINQ, I would recommend the way above. Extend your LINQ class and add a property that concatenates these fields for you. Hope that helps? :)
Tommy
Now that I reread that, I will ask what kind of advice are you looking for? Once you extend that class, you can query/filter or any other LINQ-y stuff such as: Dim q = From d in db.teachers where d.fullName = 'Some Guy'. The extended class will take care of the concatenation. I suppose my only caveat would be to check for null, b/c you will get an exception if you try and append a null string.
Tommy
With "at DB level" I meant by using a View instead of a table or something (I don't have a lot of experience).Defining fullname in a LINQ partial class probably works nicer but being able to select fullname from the database regardless of the programming language used seems like a better practise.
kversch
A: 

Create an anonymous projection that contains the data you need:

var teachers = 
    from x in dc.teachers 
        select new{Teacher=x, FullName=x.FirstName+" "+x.LastName}
spender