George Bora
George Bora

Reputation: 1650

ASP.NET Error when binding a GridView to a List of Objects?

Error Message:

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

I have a ASP.NEt application in which I try to bind a GridView to a List<T> objects which from what I can tell on the net it should be possible.

This is my GridView:

<asp:GridView ID="FormProprietari" runat="server">
        <Columns>
            <asp:TemplateField >
                 <ItemTemplate> 
                    <%#((Lab_TAP_web.Proprietar)Container.DataItem).NumeProprietar%> 
                 </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField >
                 <ItemTemplate> 
                    <%#((Lab_TAP_web.Proprietar)Container.DataItem).PrenumeProprietar%> 
                 </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField >
                 <ItemTemplate> 
                    <%#((Lab_TAP_web.Proprietar)Container.DataItem).ProprietarID%> 
                 </ItemTemplate>
            </asp:TemplateField>
        </Columns>

    </asp:GridView>

And this is the function in which I add a new object of the Proprietar class I defined to the database then rebind the gridview to show it, I should mention that intially the database is empty and so is the gridview i,e it doesn't show up.

protected void Button2_Click(object sender, EventArgs e)
        {
            var Nume = TBNumeProprietar.Text;
            var Prenume = TBPreNumeProprietar.Text;

            MyCars db = DBSilo.db;

            Proprietar newOwner = new Proprietar();
            newOwner.NumeProprietar = Nume;
            newOwner.PrenumeProprietar = Prenume;
            newOwner.ProprietarID = (db.Proprietari.Count() + 1);
            //newOwner.ProprietarID = 1;



            db.Proprietari.InsertOnSubmit(newOwner);
            db.SubmitChanges();

            try
            {
                FormProprietari.DataSource = db.Proprietari.ToList();
            }
            catch (Exception)
            {

                throw;
            }
            FormProprietari.DataBind();           
        }

The problem being that I checked the List<Proprietar> which is the data source with breakpoints and the list always contains a Proprietar object.

Does anyone have a idea what I did wrong?

Upvotes: 1

Views: 1234

Answers (1)

Win
Win

Reputation: 62260

Moved from comment to Answer.

Please make sure you have getter and setter for each property of Proprietar class like this -

public class Proprietar
{
    public string NumeProprietar { get; set; }
    public string PrenumeProprietar { get; set; }
    public int ProprietarID { get; set; }
}

Upvotes: 1

Related Questions