1

I have class Person, having two properties First Name and Last Name, if I set array of person as Data Source to GridView how can I show both First Name and Last Name in one column?/

Thanx

2 Answers 2

1

Use tempate field and Eval method:

<asp:GridView runat="server" ID="MyGrid" AutoGenerateColumns="false" 
  DataSourceId="...">       
  <Columns>         
    <asp:TemplateField>         
      <ItemTemplate>         
        <%# Eval("FirstName") %>&nbsp;<%# Eval("LastName") %>
      </ItemTemplate>         
    </asp:TemplateField>     
  </Columns> 
</asp:GridView>
Sign up to request clarification or add additional context in comments.

Comments

0

If you don't mind doing it i the code-behind, here's how.

Put a TemplateField in the GridView, containg a Label in the ItemTemplate, and wire up the RowDataBound event of the GridView to a handler:

<asp:GridView runat="server" ID="PeopleGridView" AutoGenerateColumns="false" OnRowDataBound="PeopleGridView_OnDataBound" >
    <Columns>
        <asp:TemplateField>
        <ItemTemplate>
            <asp:Label runat="server" ID="NameLabel" />
        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

In the handler, get the DataItem and cast it to your Person class. Locate the Label control and set the Text to the properties from the class:

protected void PeopleGridView_OnDataBound(object sender, GridViewRowEventArgs e)
{
    // Make sure it's a DataRow - this will fail for HeaderRow, FooterRow etc
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // Get the DataItem and cast it
        Person currentPerson = (Person) e.Row.DataItem;
        // Locate the Label and set it's text
        ((Label) e.Row.FindControl("NameLabel")).Text = currentPerson.firstName + " " + currentPerson.lastName;
    }
}

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.