将DataGridViewComboBoxColumn绑定到DataTable不起作用

时间:2015-11-02 14:18:53

标签: c# winforms

我将DataGridViewComboBoxColumn绑定到DataTable,但列的单元格未显示绑定表。 任何的想法? 为了测试DataTable,我将它绑定到正常ComboBox,这显示了预期的行为。

 private void populateDataGW()
    {
        int addressesCount = data.Length / 186;
        TestingAdrress[] addressArray = new TestingAdrress[addressesCount];
        addressArray = getArray();
        DataGridViewRow dtRow = new DataGridViewRow();

        dtTableCmbBx = getAllCustomers();
        DataGridViewComboBoxColumn cmBxCol = new DataGridViewComboBoxColumn();
        //Binding here is not working
        cmBxCol.DataSource = dtTableCmbBx;
        cmBxCol.ValueMember = "Customer_ID";
        cmBxCol.DisplayMember = "Name";
        dtGrViTestAddress.Columns.Add(cmBxCol);
        //code for "normal" combobox
        comboBox1.DataSource = dtTableCmbBx;
        comboBox1.DisplayMember= "Name";
        comboBox1.ValueMember = "Customer_ID";

        DataGridViewButtonCell btnCell = new DataGridViewButtonCell();
        btnCell.Value = "Hinzufügen";

        for (int i=0; i< addressArray.Length;i++)
        {
            dtGrViTestAddress.Rows.Add();
            dtGrViTestAddress.Rows[i].Cells[0].Value = addressArray[i].Name;
            dtGrViTestAddress.Rows[i].Cells[1].Value = addressArray[i].Street;
            dtGrViTestAddress.Rows[i].Cells[2].Value = addressArray[i].PostalCode;
            dtGrViTestAddress.Rows[i].Cells[3].Value = addressArray[i].City;
            dtGrViTestAddress.Rows[i].Cells[5] = btnCell;                
        }
    }

以下是截图:

enter image description here

2 个答案:

答案 0 :(得分:0)

我发现了这个问题。我希望datagridview是readOnly,这就是为什么组合框没有显示其中的项目,现在我改变了这个属性,我为每个列分隔设置它,并让组合框列为readOnly = false

答案 1 :(得分:0)

  

方法1:使用Linq

var details = (from x in db.Details
               orderby x.Datetime descending
               where x.RaisedBy == "xyz"
               select x).ToList();

comboBox1.ValueMember ="id";
comboBox1.DataSource = details;

comboBox2.ValueMember ="Name";
comboBox2.DataSource = details;

comboBox3.ValueMember ="Street";
comboBox3.DataSource = details;

comboBox4.ValueMember ="PostalCode";
comboBox4.DataSource = details;
  

方法:2

var combocolumnA = new DataGridViewComboBoxColumn();
combocolumnA.HeaderText = "ID"; // grid header name
combocolumnA.ValueMember = "id";// database Column name
combocolumnA.DataSource = details;
GV.Columns.Add(combocolumnA);
combocolumnA.Width = 100;

var combocolumnB = new DataGridViewComboBoxColumn();
combocolumnB.HeaderText = "Name";
combocolumnB.ValueMember = "Name";
combocolumnB.DataSource = details;
GV.Columns.Add(combocolumnB);
combocolumnB.Width = 150;

编辑:

再告诉您一件事...如果要在网格视图中获取数据,假设您从组合框中选择了名称,那么数据会根据数据库自动更改gridview的所有字段吗?