Reputation: 21
I want to bind multiple attributes from the database on my grid view, so I have (first name, middle name and last name) and I want to concatenate them in one column of my grid view (name)
<asp:GridView ID="GV1" runat="server" AutoGenerateEditButton="true"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label
ID="edtName"
runat="server"
Text='<%# Bind("Name") %>'
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
So, how do I bind them? I'm using visual studio 2013, asp.net with c#, Thanks.
Upvotes: 2
Views: 3318
Reputation: 668
You can Use Eval like below :
Text='<%# string.Concat(Eval("FirstName"), " ", Eval("LastName"))%>'
Upvotes: 0
Reputation: 24957
There are two ways to do that:
1) Using string concatenation
The string concatenation on Text
property does not allow multiple Bind
methods for data binding, hence Eval
should be used here.
+
operator version
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="edtName" runat="server" Text='<%# Eval("firstname") %> + ' ' + <%# Eval("middlename") %> + ' ' + <%# Eval("lastname") %>' />
</ItemTemplate>
</asp:TemplateField>
String.Format version
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="edtName" runat="server" Text='<%# String.Format("{0} {1} {2}", Eval("FirstName"), Eval("MiddleName"), Eval("LastName")) %>' />
</ItemTemplate>
</asp:TemplateField>
2) Modify query with AS aliasing
Use COALESCE
operator to combine all related fields into single string and give an alias which has same key as defined in label's Bind
:
SELECT COALESCE(FirstName, '') || COALESCE(MiddleName, '') || COALESCE(LastName, '') AS Name FROM TableName ...
Upvotes: 2