Somebody
Somebody

Reputation: 2779

binding a GridView to a List in asp.net c#

This is the first time that I'm doing this, so I need a little bit of help,

I have this code behind:

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

in design:

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

But trying to run the web app, I'm getting the following error:

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.

Do I have to do anything else, to make this work?

Upvotes: 0

Views: 3173

Answers (2)

Sam Sussman
Sam Sussman

Reputation: 1045

You can bind to lists gridviews, but your class has to use PROPERTIES, not variables.

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

Upvotes: 1

Servy
Servy

Reputation: 203802

Databinding relies on using properties rather than fields, as the error message you got indicates. You can easily change your code so that Trucks uses properties instead:

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

If you make that change everything should work.

Note that there are a number of subtle differences between properties and public fields. A property is effectively syntactic sugar around methods, so public string Placa {get;set;} would be transformed into something similar to:

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

As for the differences between methods and fields, that's probably beyond the scope of this question.

Upvotes: 4

Related Questions