GridView某一列要绑定的数据是某个类对象的属性,代码该如何写?

2024-12-03 06:43:59
推荐回答(1个)
回答1:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>














<%#Eval("Name")%>




<%#((Person)(Container.DataItem)).Sex%>




<%#new Person().Test%>









using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) return;
gvPerson.DataSource = Person.GetData();
gvPerson.DataBind();
}
}

class Person
{
public int ID { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
public string Test
{
get { return "Test"; }
set { Test = value; }
}

public static List GetData()
{
return new List()
{
new Person(){ID=1,Name="张三",Sex="男"},
new Person(){ID=2,Name="李四",Sex="男"},
new Person(){ID=3,Name="王八",Sex="男"},
new Person(){ID=4,Name="翠花",Sex="女"}
};
}
}