开发者

How to show two properties in one column of GRid View asp.net C#

开发者 https://www.devze.com 2023-02-09 13:54 出处:网络
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?/

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开发者_如何学Python


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>


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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消