【问题标题】:Gridview using a generic list as DataSource and Auto-generating columns使用通用列表作为数据源和自动生成列的 Gridview
【发布时间】:2025-12-23 01:50:12
【问题描述】:

我正在寻找使用通用列表加载 GridView 并自动生成列。我收到一个异常,它没有正确的属性来允许它自动生成列。

例外

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

网格视图

<asp:GridView ID="GV1" runat="server" AutoGenerateColumns="true"></asp:GridView>

页面加载

    //LINQ query to populate list
    List<student> su = new List<student>();
    dbDataContext db = new dbDataContext();
    var q = from c in db.data_table
            where c.processed == false
            orderby c.date_complete descending
            select c;
     //iterate through results and add to list
     foreach(var c in q)
     {
         student s = new student { name = c.name, address = c.address };
         su.Add(s);
     } 

     //Load GridView
     GV1.DataSource = su;
     GV1.DataBind(); //Exception thrown here

学生班

public class student
{
    public string name;
    public string address;
}

感谢您的任何想法或建议,如果我完全错了,请随时告诉我。

【问题讨论】:

    标签: c# linq data-binding gridview


    【解决方案1】:

    尝试调整您的 student 类并将您的字段更改为如下属性:

    public class student
    {
       public string name { get; set; }
       public string address { get; set; }
    }
    

    【讨论】:

    • 这回答了我的一个类似问题。我不明白它为什么起作用。为什么我可以手动访问student.nameGridView 除非我添加访问器才能访问?
    • 我不能具体说,我只能告诉你,网格只会访问属性,不会访问字段。我可以猜测当它进行反射时,它会反射到公共属性 (BindingFlags.GetProperty) 而不是公共字段 (BindingFlags.GetField)。
    • 经过数小时的搜索,您是上帝派来的。这个答案解决了我的问题。谢谢!