DataGridView数据绑定 [英] DataGridView databinding

查看:109
本文介绍了DataGridView数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I give a simple example to explain what I want:

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

I defined a class called Student, it has two properties: Name and Subjects.

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

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

I created two instances of Student class, for example:

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

然后我创建一个列表StudentList:

Then I create a List studentList:

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

我的问题是,有什么方法可以对这个 studentList进行数据绑定 DataGridView ,如下所示:

My question is, is there any way I can databind this studentList with a DataGridView, something like the following:

dataGridView.DataSource = studentList;

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

The first column is the student name and the second column is a combobox which shows all the subjects for the student.

谢谢您的时间。

推荐答案

类似的方法将起作用:


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

  1. Add a RowDataBound event to your grid and create a template column to hold the dropdownlist for the subjects:

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

然后在代码上像这样处理RowDataBound事件:

Then on code behind handle the RowDataBound event as so:

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


渲染:

顺便说一句,您的学生班级应该看起来像这样:

BTW, your Student class should look like this:

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

这篇关于DataGridView数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆