2016-04-15 49 views
0

我已将DataGridViewComboBox添加到绑定DataGridViewgrdBOOK),DataGridViewComboBox将替换第3列以允许用户选择。我努力将DataGridViewComboBox的默认值设置为等于第3列的值,因此如果值正确,则不需要用户选择。设置DataGridViewComboBox默认等于现有DataGridView列

我把下面的代码从net,但我得到一个错误:

DataGridViewComboBoxCell value is not valid.

我想到了一个ComboBox细胞可以作为一个正常的DataGridView细胞治疗,但(见下面的代码)产生一个错误当一个字符串被添加到ComboBox列?我拖网了几天,但没有任何作品,请提出任何建议?

public void BOOK_COMBO2()  
     { 
      DataGridViewComboBoxCell cb_cell = new DataGridViewComboBoxCell(); 
      DataGridViewComboBoxColumn cb_col = new DataGridViewComboBoxColumn(); 

      // Contract field 
      cb_col.Items.AddRange("YEARLY", "MONTHLY", ""); 
      cb_col.FlatStyle = FlatStyle.Flat; 
      cb_col.HeaderText = "newCONTRACT"; 
      cb_col.Width = 50; 
      cb_col.ValueType = typeof(string); 

      // Add ComboBox and test 
      grdBOOK.Columns.Insert(5, cb_col); 
      grdBOOK.Rows[14].Cells[4].Value = "zzz";  // No error adding string to normal dgv column 
      grdBOOK.Rows[14].Cells[5].Value = "xxx";  // Error adding string to dgvcombobx column 

      //copy old values to new combobox and set as default 
      foreach (DataGridViewRow item in grdBOOK.Rows) 
      { 
       item.Cells[5].Value = item.Cells[3].Value;  
      } 
      //hide original column 
      grdBOOK.Columns[3].Visible = false; 
     } 
+0

你从哪里调用这个'BOOK_COMBO2'方法? – OhBeWise

+0

此外,更重要的是,请验证该列中的值始终是您的选项之一:'“年”,“月”,“'”。如果有的价值不是其中之一,你会得到这个错误;是的,case和空格很重要 - ''Yearly''和''“''会抛出错误。 – OhBeWise

+0

我从Main类调用方法,并在设计时将datagridview添加到主窗体。我没有得到任何项目列表的错误,错误是由从datagridview列中的一个值复制到datagridviewcombobox列引起的。这行代码:''item.Cells [5] .Value = item.Cells [3] .Value; '' – Zeus

回答

0

经过对网络的更多研究,恕我直言,使用ContextMenuStrip是实现这一目标的更好方法。链接here。 A ContextMenuStrip有更好的方法,事件,属性等。我希望这可以帮助其他人寻找解决方案。

0
private void dataGridView1_DataError(object sender, 
      DataGridViewDataErrorEventArgs e) 
     { 
      // If the data source raises an exception when a cell value is 
      // commited, display an error message. 
      if (e.Exception != null && 
       e.Context == DataGridViewDataErrorContexts.Commit) 
      { 
       MessageBox.Show(""); 
      } 
     } 




private void Form1_Load(object sender, EventArgs e) 
    { dataGridView1.DataError += 
       dataGridView1_DataError;}