【问题标题】:Set DataGridViewComboBox default equal to existing DataGridView column将 DataGridViewComboBox 默认设置为等于现有 DataGridView 列
【发布时间】:2016-04-15 12:05:40
【问题描述】:

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

我从net 中提取了以下代码,但出现错误:

DataGridViewComboBoxCell 值无效。

我认为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;
        }

【问题讨论】:

  • 你从哪里调用这个BOOK_COMBO2方法?
  • 另外,更重要的是,验证该列中的值是否始终是您的选项之一:"YEARLY", "MONTHLY", ""。如果值不是其中之一,您将收到该错误;是的,大小写和空格很重要 - "Yearly"" " 会抛出错误。
  • 我从 Main 类调用该方法,并且在设计时将 datagridview 添加到主窗体中。我没有得到项目列表的任何错误,该错误是由将值从 datagridview 列之一复制到 datagridviewcombobox 列引起的。这行代码:item.Cells[5].Value = item.Cells[3].Value;

标签: c# datagridview datagridviewcombobox


【解决方案1】:

在网上进行更多研究后,恕我直言,使用ContextMenuStrip 是实现此目的的更好方法。链接hereContextMenuStrip 有更好的方法、事件、属性等。我希望这可以帮助其他寻找解决方案的人。

【讨论】:

    【解决方案2】:
      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;}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      • 2013-11-05
      • 2011-10-11
      • 2014-06-01
      • 1970-01-01
      • 2011-08-24
      • 2013-03-24
      相关资源
      最近更新 更多