基本上我在Windows窗体中有一个数据网格视图。我添加了一个组合框作为列

时间:2014-11-28 13:39:09

标签: winforms data-binding datagridview combobox

这是我的对象结构

       class object 
       {
           string projectname;
           string projectid;
           list<string> associated_students;
       }

//我绑定到网格的列表

       list<objects> objectList = getList();
       dataGridView.Source =objectList;

现在我想将datagrid中的组合框与列表&#34; associated_students&#34;

绑定在一起

1 个答案:

答案 0 :(得分:0)

如果我理解了这个问题,您希望每一行都绑定到对象列表中的一个对象,并且您希望第三列显示该对象的唯一关联学生列表的组合框。如果我是正确的,一个简单的搜索会导致类似的问题:

How do I set up a DataGridView ComboBoxColumn with a different DataSource in each cell?

要解决此问题,您需要手动绑定每一行。我能够复制你的问题,并提出了这个解决方案:

你的班级&#34;对象&#34;

public class Assignment
{
  public Assignment()
  {
    this.Associated_Students = new List<string>();
  }

  public string ProjectName { get; set; }
  public string ProjectID { get; set; }
  public List<string> Associated_Students { get; set; }
}

在Form1中:

public Form1()
{
  InitializeComponent();

  this.Assignments = new List<Assignment>()
  {
    new Assignment()
    {
      ProjectID = "1",
      ProjectName = "First",
      Associated_Students = new List<string>() { "Me", "You", "Him", "Her" }
    },

    new Assignment()
    {
      ProjectID = "2",
      ProjectName = "Second",
      Associated_Students = new List<string>() { "Foo", "Bar" }
    }
  };

  this.BindDGViewToList();
}

public List<Assignment> Assignments { get; set; }

public void BindDGViewToList()
{
  DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
  col1.Name = "Project Name";
  col1.ValueType = typeof(string);
  dataGridView1.Columns.Add(col1);

  DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn();
  col2.Name = "Project ID";
  col2.ValueType = typeof(string);
  dataGridView1.Columns.Add(col2);

  DataGridViewComboBoxColumn col3 = new DataGridViewComboBoxColumn();
  col3.Name = "Associated Students";
  col3.ValueType = typeof(string);
  dataGridView1.Columns.Add(col3);

  for (int i = 0; i < this.Assignments.Count; i++)
  {
    DataGridViewRow row = (DataGridViewRow)(dataGridView1.Rows[0].Clone());

    DataGridViewTextBoxCell textCell = (DataGridViewTextBoxCell)(row.Cells[0]);
    textCell.ValueType = typeof(string);
    textCell.Value = this.Assignments[i].ProjectName;

    textCell = (DataGridViewTextBoxCell)(row.Cells[1]);
    textCell.ValueType = typeof(string);
    textCell.Value = this.Assignments[i].ProjectID;

    DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)(row.Cells[2]);
    comboCell.ValueType = typeof(string);
    comboCell.DataSource = this.Assignments[i].Associated_Students;

    dataGridView1.Rows.Add(row);
  }
}

注意:这将显示您要求的内容,但您必须处理更新数据。我建议在List对象上研究BindingList。可能有更好的解决方案,但这对我来说很快。