簡體   English   中英

將DataGridViewComboBox設置為默認等於現有DataGridView列

[英]Set DataGridViewComboBox default equal to existing DataGridView column

我已經將DataGridViewComboBox添加到綁定的DataGridViewgrdBOOK ), DataGridViewComboBox將替換第3列,以允許用戶選擇。 我正在努力將DataGridViewComboBox的默認值設置為等於第3列的值,因此如果該值正確,則不需要用戶選擇。

我從網上提取了下面的代碼,但出現錯誤:

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;
        }

在網上進行了更多研究之后,使用ContextMenuStrip IMHO是實現此目的的更好方法。 鏈接到這里 ContextMenuStrip具有更好的方法,事件,屬性等。我希望這可以幫助其他人尋找解決方案。

  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;}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM