2

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.

6
  • you can try doing something like <%# Bind("firstname") %>+' '+<%# Bind("middlename") %>'+' '+'<%# Bind("lastname") %>' Commented Aug 6, 2018 at 9:01
  • 2
    You can have multiple binds: Text='<%# string.Format("{0} {1} {2}", Bind("FirstName"), Bind("MiddleName"), Bind("LastName")) %>' . Or change your query statement to concatenate all three to single string (SELECT FirstName + MiddleName + LastName AS Name, ...) Commented Aug 6, 2018 at 9:02
  • Dear Tetsuya Yamamoto, first way it didn't work with me, the exception message is (CS0103: The name 'Bind' doesn't exist in the current context). Commented Aug 6, 2018 at 9:16
  • @ShahadHassan I found that you cannot use Bind multiple times, but you can use Eval for all of these: Text='<%# string.Format("{0} {1} {2}", Eval("FirstName"), Eval("MiddleName"), Eval("LastName")) %>'. Commented Aug 6, 2018 at 9:20
  • Yes it works right now, Thank you Mr. Yamamoto :) Commented Aug 6, 2018 at 9:26

2 Answers 2

2

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

Comments

0

You can Use Eval like below :

Text='<%# string.Concat(Eval("FirstName"), " ", Eval("LastName"))%>'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.