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

后端 未结 2 1539
春和景丽
春和景丽 2021-01-24 13:44

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 colu

相关标签:
2条回答
  • 2021-01-24 14:18

    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 讨论(0)
  • 2021-01-24 14:36

    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>
    
    0 讨论(0)
提交回复
热议问题