0

这是我第一次这样做,所以我需要一点帮助,

我后面有这段代码:

List<Trucks> FinalListOfTrucks = new List<Trucks>();
    public class Trucks
    {
        public string Placa;
        public string Lock;
        public string Event;
        public DateTime Date;
        public string TipoCamion;
        public string Person;
        public string MissedDate;
    }

    protected void btnProcess_Click(object sender, EventArgs e)
        {
            Trucks item = new Trucks();
            item.Placa = "MA2323";
            item.Lock = "lock1";
            item.Event = "Event1";
            item.Date = DateTime.Now;
            item.TipoCamion = "TRUCK1";
            item.Person = "JULIAN";
            item.MissedDate = "";
            FinalListOfTrucks.Add(item);

            gvOriginal.DataSource = FinalListOfTrucks;
            gvOriginal.DataBind();
}

在设计中:

<asp:Button ID="btnProcess" runat="server" Text="Process" 
        onclick="btnProcess_Click" />
    <asp:GridView ID="gvOriginal" runat="server"></asp:GridView>

但尝试运行网络应用程序时,我收到以下错误:

The data source for GridView with id 'gvOriginal' did not have any properties or attributes from which to generate columns. Ensure that your data source has content.

我还需要做其他事情来完成这项工作吗?

4

2 回答 2

4

正如您收到的错误消息所示,数据绑定依赖于使用属性而不是字段。您可以轻松更改代码,以便Trucks使用属性:

public class Trucks
{
    public string Placa { get; set; }
    public string Lock { get; set; }
    public string Event { get; set; }
    public DateTime Date { get; set; }
    public string TipoCamion { get; set; }
    public string Person { get; set; }
    public string MissedDate { get; set; }
}

如果你做出改变,一切都应该工作。

请注意,属性和公共字段之间存在许多细微差别。属性实际上是方法周围的语法糖,因此public string Placa {get;set;}将转换为类似于:

private string _placa;
public string GetPlaca() { return _placa; }
public void SetPlaca(string value) { _placa = value; }

至于方法和字段之间的区别,这可能超出了这个问题的范围。

于 2012-11-01T20:02:25.817 回答
1

您可以绑定到列表网格视图,但您的类必须使用属性,而不是变量。

public class Trucks
{
    public string Placa{get;set;}
    public string Lock{get;set;}
    public string Event{get;set;}
    public DateTime Date{get;set;}
    public string TipoCamion{get;set;}
    public string Person{get;set;}
    public string MissedDate{get;set;}
}
于 2012-11-01T20:03:11.073 回答