将值添加到多个datagridview列,并将所有记录添加到另一个datagridview

时间:2014-05-06 12:00:53

标签: c# list object button datagridview

嗨,这是我的要求 我有一个datagridview显示每行的学生详细信息。每行都是学生对象。

我有四行或多行。 (在数据网格视图中表示最多4个或最少2个学生)。我想通过单击按钮从文本框中添加这些学生记录单个组ID,并添加到另一个datagridview。每个行组id列应该修改为在文本框中给出的组ID和所有行中的datagridview应该添加到第二个网格。

           **//In button click event
           for (int rc = 0; rc < (dgvSorted.Rows.Count);rc++ )
            {
                foreach (DataGridViewRow row in dgvSorted.Rows)
                {
                     Student studobj = new Student();
                          studobj.idNumber =  
                   dgvSorted.Rows[row.Index].Cells[0].Value.ToString();
                    studobj.fName =dgvSorted.Rows[row.Index].Cells[1].Value.ToString();
                    studobj.lName =dgvSorted.Rows[row.Index].Cells[2].Value.ToString();
                    studobj.mailE  dgvSorted.Rows[row.Index].Cells[3].Value.ToString();

                    studobj.grId = txtGrId.Text;
                    lstStudentFNL.Add(studobj);
                    BindingSource binding = new BindingSource();
                    binding.DataSource = lstStudentFNL;
                    dgvFinal.DataSource = binding;
                    dgvSorted.Rows.RemoveAt(row.Index);
                }** 
   **List<Student> lstStudentFNL = new List<Student>();**

但是这只会添加一条记录,它不会将网格中的所有记录添加到分配groupid的第二个网格中。谁能告诉我怎么做?

1 个答案:

答案 0 :(得分:1)

如果对两个DataGridView使用数据绑定,则工作示例如下所示:

string groupIdFromTextBox = "xyz";

            List<Student> students = new List<Student>();
            students.Add(new Student { Id = Guid.NewGuid(), LastName = "l1", FirstName = "f1", EMail = "e1" });
            students.Add(new Student { Id = Guid.NewGuid(), LastName = "l2", FirstName = "f2", EMail = "e2" });
            students.Add(new Student { Id = Guid.NewGuid(), LastName = "l3", FirstName = "f3", EMail = "e3" });
            students.Add(new Student { Id = Guid.NewGuid(), LastName = "l4", FirstName = "f4", EMail = "e4" });

            BindingSource dgvSortedBindingSource = new BindingSource();
            dgvSortedBindingSource.DataSource = students;

            List<Student> students2 = new List<Student>();
            BindingSource dgvSortedBindingSource2 = new BindingSource();
            dgvSortedBindingSource2.DataSource = students2;

            // This goes to your click event
            foreach (Student s in dgvSortedBindingSource.List)
            {
                s.GroupId = groupIdFromTextBox;
                dgvSortedBindingSource2.Add(s);
            }

            dgvSortedBindingSource.Clear();
            // This goes to your click event