在 C# 中向 DataGrid 插入新行,且具有不同的列

3
我正在尝试在 C# 中向 DaraGridView 插入一行新数据,但是它只有来自 DataBindingSource 的 6 行数据中的 3 行(这是一个包含一个 DataTable 的数据集)。
以下是我尝试编写的代码,但它引发了异常。异常是无法将类型为 dataset 的 obj 转换为 binding source,在弱委托列表的方法 public void Invoke(params object[] args) 中。
private void cmdNewRow_CustomExecute(object sender,
    ExecutionEventArgs<ICommandButtonExecutor> e)
{
    Fev018DataSet ds = (Fev018DataSet)(((BindingSource)
        FahrzeugBarcodeBindingSource.DataSource).DataSource);
    int a = ds.Tables[0].Rows.Count;
    ds.Tables[0].NewRow();
    customGridViewBarcodes.AddNewRow();
    bool locked = false;
    try
    {
        while (!locked)
        {
            locked = Monitor.TryEnter(this, 100);
            if (!locked)
                Application.DoEvents(); // do events to prevent 
            // prevent freezing von Invokes
        }
        if ((methodInfo == null) || (target == null)) return;
        try
        {
            if (target.IsAlive)
                methodInfo.Invoke(target.Target, args);
        }
        catch (TargetInvocationException ex)
        {
            // Get the _remoteStackTraceString of the Exception class
            FieldInfo remoteStackTraceString = typeof(Exception)
                .GetField("_remoteStackTraceString",
                BindingFlags.Instance | BindingFlags.NonPublic); // MS.Net
            if (remoteStackTraceString == null)
                remoteStackTraceString = typeof(Exception)
                .GetField("remote_stack_trace",
                BindingFlags.Instance | BindingFlags.NonPublic); // Mono
            // Set the InnerException._remoteStackTraceString
            // to the current InnerException.StackTrace
            remoteStackTraceString.SetValue(ex.InnerException,
                ex.InnerException.StackTrace + Environment.NewLine);
            // Throw the new exception
            throw ex.InnerException;
        }
    catch (Exception)
    {
        throw;
    }
    finally
    {
        if (locked)
            Monitor.Exit(this);
    }
}

你有任何想法吗?


在哪一行准确地说? - Soner Gönül
是的,你在哪里准确地得到了异常? - Anurag
在弱委托列表的方法public void Invoke(params object[] args)中。cs: - StefanaB
但是我们在发布的代码中没有看到Invoke方法,请把完整的代码放上。 - Anurag
@StefanaB:你的代码一点也没有帮助我们理解情况。你能否检查一下你的代码中获取的绑定源类型是什么?异常信息显示无法转换为数据集,因此在转换时出现了问题。 - Anurag
我已经编辑了带有抛出异常函数的问题。 - StefanaB
1个回答

2
当您在此行收到此异常时,它无法将数据集类型的obj转换为绑定源。
Fev018DataSet ds = (Fev018DataSet)(((BindingSource)FahrzeugBarcodeBindingSource.DataSource).DataSource);

这句话的意思是,FahrzeugBarcodeBindingSource.DataSource后面的对象不是BindingSource类型,而是DataSet类型。

这一行应该改为:

Fev018DataSet ds = (Fev018DataSet)FahrzeugBarcodeBindingSource.DataSource; 

或者

DataSet ds = (DataSet)FahrzeugBarcodeBindingSource.DataSource;

可能是在您的代码其他地方,您错误地将 DataSet 分配给了 FahrzeugBarcodeBindingSource.DataSource,而不是 BindingSource


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接