C# DataGridViewComboxCell.Value上的FormatException

C# DataGridViewComboxCell.Value上的FormatException,c#,winforms,datagridview,datagridviewcomboboxcell,C#,Winforms,Datagridview,Datagridviewcomboboxcell,我有一个我想不出来的问题 我有一个DataGridViewComboxCell List<ComboBoxItem> klanten = new List<ComboBoxItem>(); foreach (ICustomer customer in CustomerFactory.CreateCustomers()) { klanten.Add(new ComboBoxItem(customer.Naam, customer.Id)); } klanten.A

我有一个我想不出来的问题

我有一个DataGridViewComboxCell

List<ComboBoxItem> klanten = new List<ComboBoxItem>();
foreach (ICustomer customer in CustomerFactory.CreateCustomers())
{
     klanten.Add(new ComboBoxItem(customer.Naam, customer.Id));
}
klanten.Add(new ComboBoxItem("Klant aanvraag", -1));

uxInvoerenKlant.DataSource = klanten;
uxInvoerenKlant.DisplayMember = "Text";
uxInvoerenKlant.ValueMember = "Value";
klantindex
是需要选择的客户,因为它是从组合框中检索的。在我看来,这是一种正确的对象

在此之后,将引发
datagridview\u dataerror
事件,在该事件中,我将获得格式异常和以下异常文本

DataGridViewComboxCell值无效


有什么问题吗?

我想可能是你的-1值。可能您需要从0开始您应该将所选值添加到组合框的items集合中,由于在
ComboBoxColumn
Item
集合中找不到分配的值,因此会引发异常

尝试使用
Add

(dataGridView1.Columns[0] as DataGridViewComboBoxColumn).Items.Add

我自己发现了问题

uxUrenInvoeren[collumnIndex,row.Index].Value
包含ComboBoxItem的值,而不是ComboxItem本身。代码现在如下所示:

ComboBoxItem item = uxInvoerenKlant.Items[klantIndex] as ComboBoxItem;
if (item != null)
{
    uxUrenInvoeren[collumnIndex, row.Index].Value = item.Value;
}
这样做很顺利

谢谢你的帮助

解决方案:

Private Sub gvPrint_DataError(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles gvPrint.DataError
    If e.Context = DataGridViewDataErrorContexts.Formatting Or e.Context = DataGridViewDataErrorContexts.PreferredSize Then
        e.ThrowException = False
    End If
End Sub

UxInverenceLant是dataGridView1.Columns[0]的名称,据我所知,它将替换您的:(dataGridView1.Columns[0]作为DataGridViewComboBoxColumn)。我需要comboboxItem,因为我需要文本和值,因为customerName和customerIduxInvoerenKlant将替换0,我认为您可以将其作为Add(新ComboxItem)来执行……值将基于文本和值进行控制,希望这些是comboboxItem的属性您几乎是对的,UxurenVoeren[collumnIndex,row.Index].值为-1,但这不是问题所在。我发布了解决方法作为答案。问题使用C,请在答案中使用C。
Private Sub gvPrint_DataError(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles gvPrint.DataError
    If e.Context = DataGridViewDataErrorContexts.Formatting Or e.Context = DataGridViewDataErrorContexts.PreferredSize Then
        e.ThrowException = False
    End If
End Sub