繁体   English   中英

在DataGridView的特定单元格中设置ComboBox

[英]Set ComboBox in Specific Cell in a DataGridView

上周,我问了同样的问题,由于用户@Aaron,最终得到了解决我问题的方法。 但是,我再问一遍,因为该代码在一个项目中可以完美地工作,但是在几乎完全相同的条件下(例如,列数/行数,变量类型,DGV的填充方式)却不能在另一个项目中工作。

//This is my code to go through each cell in the DataGridView.
for (int i = 0; i < dgvTest.RowCount; i++)
        {
            for (int j = 0; j < dgvTest.ColumnCount; j++)
            {
                foreach (Information info in frmMain._dbList)
                {
                    if (dgvTest.Rows[i].Cells[j].Value.ToString().ToLower() == info.InfoName.ToLower() && info.InfoInputType == "1")
                    {
                        DataGridViewComboBoxCell c = new DataGridViewComboBoxCell();
                        c.Items.Add("0");
                        c.Items.Add("1");
                        dgvTest.Rows[i].Cells[(j + 1)] = c;

                    }
                }
            }
        }

问题:

错误信息

一旦我奇怪地单击“确定”,它就会创建ComboBox。 如果我重复此过程,它将最终用ComboBox填充每个单元格,但是每当我将鼠标悬停在它们上方时,都会弹出相同的错误消息。

是否将单元格设置为组合框,然后尝试返回同一单元格?

解决了

简单的解决方案-必须添加c.Value =#来设置值。

为了避免上述问题。 您可以为DataGridView添加DataError事件。

试试下面的代码:

private void dgvTest_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
    try
    {
        if (e.Exception.Message.contains("DataGridViewComboBoxCell value is not valid."))
        {
            object value = dgvTest.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
            if (!((DataGridViewComboBoxColumn)dgvTest.Columns[e.ColumnIndex]).Items.Contains(value))
            {
                ((DataGridViewComboBoxColumn)dgvTest.Columns[e.ColumnIndex]).Items.Add(value);
            }
        }

        throw e.Exception;
    }
    catch (Exception ex)
    {
        MessageBox.Show(string.Format(@"Failed to bind ComboBox. "
            + "Please contact support team with below error message:"
            + "\n\n" + ex.Message));
    }
}

上面,会向用户抛出错误信息。 如果要抑制此错误。 您只需遵循以下代码:

private void dgvTest_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
    try
    {
        if (e.Exception.Message.contains( "DataGridViewComboBoxCell value is not valid."))
        {
            object value = dgvTest.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
            if (!((DataGridViewComboBoxColumn)dgvTest.Columns[e.ColumnIndex]).Items.Contains(value))
            {
                ((DataGridViewComboBoxColumn)dgvTest.Columns[e.ColumnIndex]).Items.Add(value);
            }
        }
    }
    catch (Exception ex)
    {
        //do nothing
    }
}

必须将ComboBox的初始值设置为某些值。

c.Value = #

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM