【问题标题】:DataGridView databindingDataGridView 数据绑定
【发布时间】:2013-01-10 20:12:06
【问题描述】:

我举一个简单的例子来解释我想要什么:

我定义了一个名为Student的类,它有两个属性:NameSubjects

public class Student()
{
     public string Name;
     public List<string> Subjects;
}

我创建了两个 Student 类的实例,例如:

List<string> jackSubjects = new List<string>();
jackSubjects.Add("Math");
jackSubjects.Add("Physics");
Student Jack = new Student("Jack", jackSubjects);
List<string> alanSubjects = new List<string>();
alanSubjects.Add("Accounting");
alanSubjects.Add("Science");
Student Alan = new Student("Alan", alanSubjects);

然后我创建一个 List studentList:

List<Student> studentList = new List<Student>();
studentList.Add(Jack);
studentList.Add(Alan);

我的问题是,有什么方法可以将 studentListDataGridView 进行数据绑定,如下所示:

dataGridView.DataSource = studentList;

第一列是学生姓名,第二列是combobox,显示学生的所有科目。

提前感谢您的宝贵时间。

【问题讨论】:

  • 您是否尝试将studentListdataGridView.DataSource = studentList 绑定?那么这是将list 绑定到DataGridView 的一种方法。你的主要问题是什么?

标签: c# data-binding datagridview datagridviewcomboboxcell


【解决方案1】:

这样的事情会起作用:

  1. 将 RowDataBound 事件添加到您的网格并创建一个模板列来保存主题的下拉列表:

    <asp:GridView ID="dataGridView" runat="server" AutoGenerateColumns="false" OnRowDataBound="dataGridView_RowDataBound">
       <Columns>
           <asp:BoundField DataField="Name" />
           <asp:TemplateField>
               <ItemTemplate>
                   <asp:DropDownList ID="subjects" runat="server" ></asp:DropDownList>
               </ItemTemplate>
           </asp:TemplateField>
       </Columns>
    

  2. 然后在后面的代码中处理 RowDataBound 事件:

    protected void dataGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
        var ddl = (e.Row.FindControl("subjects") as DropDownList);
        ddl.DataSource = (e.Row.DataItem as Student).Subjects;
        ddl.DataBind();
      }
    }
    

渲染:

顺便说一句,你的 Student 类应该是这样的:

public class Student
{
     public string Name {get;set;}
     public List<string> Subjects {get;set;}

     public Student(string name, List<string> subjects)
     {
         Name = name;
         Subjects = subjects;
     }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多