C#运行时错误:“DataGridViewComboBoxCell值无效”

时间:2016-06-15 22:36:14

标签: c# winforms datagridview datagridviewcombobox datagridviewcomboboxcell

我在这一天大部分时间都在工作,解决方案仍然无法解决。我的Winform应用程序包含DataGridView,其中两列是ComboBox下拉列表。奇怪的是,DataGridView似乎填充正确,但是在填充时或者当鼠标悬停或看似与DataGridVeiw相关的任何其他可触发事件时,它会引发大量错误。具体来说,我收到了System.ArgumentExceptionSystem.FormatException的两个重复错误。这两个错误的消息文本是:

  

“DataGridViewComboBoxCell值无效。要替换此默认对话框,请处理DataError事件。”

我不想仅通过处理DataError事件来掩盖此问题。 我想解决导致错误的问题。这就是我填充列表的方式:

class ManageProcsRecord
{
    public SectionType PageSection { get; set; }
    public Int32 ContentID { get; set; }
    public String Content { get; set; }
    public Int32 SummaryID { get; set; }
    public RoleType UserRole { get; set; }
    public String Author { get; set; }
    public String SysTime { get; set; }
}

public enum SectionType
{
    ESJP_SECTION_HEADER = 1,
    ESJP_SECTION_FOOTER,
    ESJP_SECTION_BODY
}

public enum RoleType
{
    ESJP_ROLE_NONE = 1,
    ESJP_ROLE_TEST_ENG,
    ESJP_ROLE_FEATURE_LEAD,
    ESJP_ROLE_TEAM_LEAD
}

List<ManageProcsRecord> records =
    this.dbif.GetProcedure(this.procList.ElementAt(selectedIndex).PrimaryKey);

foreach (ManageProcsRecord record in records)
{
    DataGridViewRow row = new DataGridViewRow();
    row.CreateCells(this.dataGridView1);
    row.Cells[0].ValueType = typeof(SectionType);
    row.Cells[0].Value = record.PageSection;
    row.Cells[1].Value = record.Content;
    row.Cells[2].Value = (record.SummaryID != -1);
    row.Cells[3].ValueType = typeof(RoleType);
    row.Cells[3].Value = record.UserRole;
    row.Cells[4].Value = record.Author;
    row.Cells[5].Value = record.SysTime;
    this.dataGridView1.Rows.Add(row);     // error fest starts here
}

有关如何解决这个问题的任何想法或建议都非常感激!

1 个答案:

答案 0 :(得分:2)

您没有解释DGV是如何填充的,但我会假设您进行了设计时间设置。如果您输入这些枚举中的名称/数据,它们将被输入为字符串,因此您会收到匹配错误。使用Enum填充它并将Type设置为这样,它不会对你大喊:

List<ProcRecord> Records = new List<ProcRecord>();

// add some records
Records.Add(new ProcRecord()
{
    Author = "Ziggy",
    PageSection = SectionType.ESJP_SECTION_BODY,
    UserRole = RoleType.ESJP_ROLE_FEATURE_LEAD
});
Records.Add(new ProcRecord()
{
    Author = "Zalgo",
    PageSection = SectionType.ESJP_SECTION_BODY,
    UserRole = RoleType.ESJP_ROLE_FEATURE_LEAD
});

// set cbo datasources
DataGridViewComboBoxColumn col = (DataGridViewComboBoxColumn)dgv1.Columns[0];
col.DataSource = Enum.GetValues(typeof(SectionType));
col.ValueType = typeof(SectionType);

col = (DataGridViewComboBoxColumn)dgv1.Columns[4];
col.DataSource = Enum.GetValues(typeof(RoleType));
col.ValueType = typeof(RoleType);

如果您有这些内容的列表,则无需手动将它们逐个复制到控件中。只需将List绑定到DGV即可。对控件中数据的编辑将直流到List:

dgv1.AutoGenerateColumns = false;
// Show Me the RECORDS!!!!
dgv1.DataSource = Records;

enter image description here

您的下一个障碍可能是SysTime显示并像日期或时间一样(如果它是这样),因为它被定义为字符串。