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

后端 未结 2 1538
春和景丽
春和景丽 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:

    
        
            
            
                
            
            
        
    
    

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

提交回复
热议问题